Javascript 如何检查字符串是否包含字符和空格,而不仅仅是空格?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2031085/
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
How can I check if string contains characters & whitespace, not just whitespace?
提问by patad
What is the best way to check if a string contains only whitespace?
检查字符串是否仅包含空格的最佳方法是什么?
The string is allowed to contain characters combinedwith whitespace, but not justwhitespace.
该字符串允许包含与空格组合的字符,但不仅仅是空格。
回答by nickf
Instead of checking the entire string to see if there's only whitespace, just check to see if there's at least one character of nonwhitespace:
与其检查整个字符串以查看是否只有空格,只需检查是否至少有一个非空格字符:
if (/\S/.test(myString)) {
// string is not empty and not just whitespace
}
回答by Paul Creasey
if (/^\s+$/.test(myString))
{
//string contains only whitespace
}
this checks for 1 or more whitespace characters, if you it to also match an empty string then replace +with *.
这将检查 1 个或多个空白字符,如果您还匹配空字符串,则将其替换+为*.
回答by FullStack
Simplest answer if your browser supports the trim()function
如果您的浏览器支持该trim()功能,最简单的答案
if (myString && !myString.trim()) {
//First condition to check if string is not empty
//Second condition checks if string contains just whitespace
}
回答by Dayson
Well, if you are using jQuery, it's simpler.
好吧,如果您使用的是 jQuery,那就更简单了。
if ($.trim(val).length === 0){
// string is invalid
}
回答by Ian Clelland
Just check the string against this regex:
只需根据此正则表达式检查字符串:
if(mystring.match(/^\s+$/) === null) {
alert("String is good");
} else {
alert("String contains only whitespace");
}
回答by slim
if (!myString.replace(/^\s+|\s+$/g,""))
alert('string is only whitespace');
回答by Rajat Saxena
I've used the following method to detect if a string contains only whitespace. It also matches empty strings.
我使用以下方法来检测字符串是否仅包含空格。它还匹配空字符串。
if (/^\s*$/.test(myStr)) {
// the string contains only whitespace
}
回答by 9me
This can be fast solution
这可以是快速解决方案
return input < "\u0020" + 1;
回答by Will Strohmeier
The regular expression I ended up using for when I want to allow spaces in the middle of my string, but not at the beginning or end was this:
当我想在字符串中间允许空格但不在开头或结尾时,我最终使用的正则表达式是这样的:
[\S]+(\s[\S]+)*
or
或者
^[\S]+(\s[\S]+)*$
So, I know this is an old question, but you could do something like:
所以,我知道这是一个老问题,但你可以这样做:
if (/^\s+$/.test(myString)) {
//string contains characters and white spaces
}
or you can do what nickfsaid and use:
或者你可以做nickf所说的并使用:
if (/\S/.test(myString)) {
// string is not empty and not just whitespace
}

