JavaScript中的空白和空字符串有什么区别 [英] What is the Difference Between Whitespace and Empty String in JavaScript

查看:68
本文介绍了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; 
    }
}

其中nI是文本输入对象.

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?

推荐答案

首先,您应该了解空字符串和空格之间的区别.

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

' '白色空格的长度是1.

The length of a white ' ' space is 1 .

空字符串''的长度为零.

如果您需要在字符串的开头和结尾都删除任意数量的空格,则可以使用trim()函数,然后可以根据需要计算长度.

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

您可以在使用trim()

这篇关于JavaScript中的空白和空字符串有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆