Aymen Kareem Aymen Kareem - 1 year ago 126
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() {
alert("Field is empty!");
return false;
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 Source

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.


You may check for empty string after using trim()

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download