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?
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?
Share Improve this question edited Oct 24, 2016 at 7:40 William asked Oct 6, 2016 at 3:13 WilliamWilliam 3302 gold badges10 silver badges23 bronze badges 4- First check if string length is not zero. This also considers a single space ` ` as valid string. Second, checks if there is at-least one non-space character. – Tushar Commented Oct 6, 2016 at 3:15
-
2
The second test makes the first redundant, it would be simpler as
/\S/.test(nI.value)
. ;-) – RobG Commented Oct 6, 2016 at 3:19 - @Tushar not sure what u mean – William Commented Oct 6, 2016 at 3:20
-
if(nI.value.trim())
will work...trim()
removes space on each end and an empty string is falsy – charlietfl Commented Oct 6, 2016 at 3:25
1 Answer
Reset to default 6First 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()