William
William

Reputation: 330

What is the Difference Between Whitespace and Empty String in JavaScript

I am checking if the user input is left empty or not using my check like that:

function myFunction() {
    if(nI.value.length<1)
    {
        alert("Field is empty!"); 
        return false; 
    }
    else 
    {   
        return true; 
    }
}

where nI is the text input object.

I read in another place we can do that through:

function isSignificant( text ){
  var notWhitespaceTestRegex = /[^\s]{1,}/;
  return String(text).search(notWhitespaceTestRegex) != -1;
}

The last function is checking for whitespace. What is the difference between checking for empty string and whitespace?

Upvotes: 3

Views: 13969

Answers (1)

Rohith K N
Rohith K N

Reputation: 871

First you should know the difference between empty string and a white space.

The length of a white ' ' space is 1 .

An empty string '' will have a length zero.

If you need to remove any number of white spaces at both starting and ending of a string you may use trim() function, then you may count the length if it is necessary.

OR

You may check for empty string after using trim()

Upvotes: 6

Related Questions