How to check if a String is empty in Javascript?

Asked

Viewed 24,310 times

10

Given the following object:

var pessoa = {
      nome: "fernando"
}

Note: sometimes I am receiving the object as follows:

var pessoa = {
      nome: ""
}

How do I check the attribute name is empty, as the second object shows?

  • @Phanpy because the insistence to edit the empty word for "vázio" with accent?!

  • @Phanpy but of which English "vázio" is correct?

  • @Phanpy Are you sure? See: http://www.dicionarioinformal.com.br/v%C3%A1zio/

  • @Phanpy before changing any question or answer, be sure what you are doing. Anything, go here and see about publishing privilege

3 answers

20


I consider the most practical way:

if (!pessoa.nome)

Well, go check it out:

  • vazio ("")
  • null
  • NaN
  • undefined
  • false
  • 0

var pessoa = {
      nome: ""
}

if (!pessoa.nome)
  console.log("Atributo vazio");

6

There are three ways to check this.

if (pessoa.nome === "") {}

or

if (!pessoa.nome) {}

or

if (pessoa.nome.length === 0) {}

2

Length checks how many characters it has.

if(pessoa.nome.length == 0)

If you have 0 it’s because it’s empty.

Or you can use exclamation ! to check if it’s fake, if it’s true is why it always has characters.

Example

var pessoa = {
  nome_1 : 'Teste',
  nome_2 : ''
};

if(pessoa.nome_1.length == 0) console.log('Vazio');
if(pessoa.nome_2.length == 0) console.log('Vazio');

if(!pessoa.nome_1.length) console.log('Vazio');    
if(!pessoa.nome_2.length) console.log('Vazio');

  • What’s wrong with my answer? The code is wrong ?

  • 2

    No problem. + 1

  • It worked here.

  • I think it is intrigue of the opposition rs +1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.