如何最好地检查字符串是否只包含空白字符?
该字符串允许包含与空格组合在一起的字符,但不允许只有空白字符。
如何最好地检查字符串是否只包含空白字符?
该字符串允许包含与空格组合在一起的字符,但不允许只有空白字符。
不要检查整个字符串是否只包含空格,只需检查是否至少有一个非空白字符:
if (/\S/.test(myString)) {
// string is not empty and not just whitespace
}
如果您的浏览器支持trim()
函数,则最简单的答案是:
if (myString && !myString.trim()) {
//First condition to check if string is not empty
//Second condition checks if string contains just whitespace
}
if (/^\s+$/.test(myString))
{
//string contains only whitespace
}
这段代码检查是否存在一个或多个空格字符,如果您想匹配空字符串,则将 +
替换为 *
。
如果你正在使用jQuery,那就更简单了。
if ($.trim(val).length === 0){
// string is invalid
}
只需使用此正则表达式检查字符串:
if(mystring.match(/^\s+$/) === null) {
alert("String is good");
} else {
alert("String contains only whitespace");
}
if (!myString.replace(/^\s+|\s+$/g,""))
alert('string is only whitespace');
我使用了以下方法来检测字符串是否仅包含空格。它也匹配空字符串。
if (/^\s*$/.test(myStr)) {
// the string contains only whitespace
}
[\S]+(\s[\S]+)*
或者
^[\S]+(\s[\S]+)*$
我知道这是一个老问题,但你可以做类似这样的事情:
if (/^\s+$/.test(myString)) {
//string contains characters and white spaces
}
或者你可以像nickf所说的那样使用:
if (/\S/.test(myString)) {
// string is not empty and not just whitespace
}
这可以是一个快速的解决方案
return input < "\u0020" + 1;
return input < " 1";
,也就是进行字母比较。只要输入的内容按照字母顺序排列在 " 1" 之前,它就会返回 true。例如:return " asdfv34562345" < "\u0020" + 1;
将会被计算为 true。 - Derek Ziemba