Javascript 如何使用javascript确定字符串是否仅包含空格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10528193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:44:11  来源:igfitidea点击:

How can I determine if a string only contains spaces, using javascript?

javascriptjquery

提问by 123

How can I determine if an input string only contains spaces, using javascript?

如何使用javascript确定输入字符串是否仅包含空格?

回答by Pranay Rana

Another good post for : Faster JavaScript Trim

另一个好帖子:更快的 JavaScript 修剪

You just need to apply trimfunction and check the length of the string. If the length after trimming is 0 - then the string contains only spaces.

您只需要应用trim函数并检查字符串的长度。如果修剪后的长度为 0 - 则字符串仅包含空格。

var str = "data abc";
if((jQuery.trim( str )).length==0)
  alert("only spaces");
else 
  alert("contains other characters");

回答by Chuck Norris

if (!input.match(/^\s*$/)) {
    //your turn...
} 

回答by Joseph

Alternatively, you can do a test()which returns a boolean instead of an array

或者,您可以执行test()返回布尔值而不是数组的 a

//assuming input is the string to test
if(/^\s*$/.test(input)){
    //has spaces
}

回答by pmrotule

The fastest solution is using the regex prototype function test()and looking for any character that is not a space or a line break \S:

最快的解决方案是使用正则表达式原型函数test()并查找任何不是空格或换行符的字符\S

if (/\S/.test(str))
{
    // found something other than a space or a line break
}

In case that you have a super long string, it can make a significant difference.

如果你有一个超长的字符串,它会产生很大的不同。

回答by u283863

if(!input.match(/^([\s\t\r\n]*)$/)) {
    blah.blah();
}