Aymen Kareem Aymen Kareem - 2 months ago 10
HTML Question

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?

Answer

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()