admin管理员组文章数量:1305124
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()
本文标签: htmlWhat is the Difference Between Whitespace and Empty String in JavaScriptStack Overflow
版权声明:本文标题:html - What is the Difference Between Whitespace and Empty String in JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741797295a2398009.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论