【发布时间】:2011-01-03 02:49:01
【问题描述】:
检查字符串是否仅包含空格的最佳方法是什么?
字符串可以包含组合和空格的字符,但不能只是空格。
【问题讨论】:
标签: javascript string whitespace
检查字符串是否仅包含空格的最佳方法是什么?
字符串可以包含组合和空格的字符,但不能只是空格。
【问题讨论】:
标签: javascript string whitespace
不要检查整个字符串是否只有空格,只需检查是否有至少一个字符 non 空格:
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
}
这将检查 1 个或多个空白字符,如果您还匹配一个空字符串,则将 + 替换为 *。
【讨论】:
好吧,如果你使用的是 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');
【讨论】:
当我想在我的字符串中间允许空格但不在开头或结尾时,我最终使用的正则表达式是这样的:
[\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
}
【讨论】:
我使用以下方法来检测字符串是否仅包含空格。它也匹配空字符串。
if (/^\s*$/.test(myStr)) {
// the string contains only whitespace
}
【讨论】:
这可以是快速的解决方案
return input < "\u0020" + 1;
【讨论】:
return input < " 1"; 这只是在做字母比较。只要输入排序小于“ 1”,它就会返回true。示例:return " asdfv34562345" < "\u0020" + 1; 计算结果为真。