正则表达式只有空格 - javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6471718/
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
regex only spaces - javascript
提问by Marco
I need to filter a field composed of only spaces; something like:
我需要过滤一个仅由空格组成的字段;就像是:
if (word == /((\s)+)/ ) return 'no name'
but it doesn't work ... any other ideas? thank you for your ideas!
但它不起作用......还有其他想法吗?谢谢你的想法!
回答by Gabi Purcaru
You should use if(/^\s+$/.test(word))
. (Notice the ^
and $
, without them the regex will hold for any string that has at least a space-like character)
你应该使用if(/^\s+$/.test(word))
. (注意^
and $
,没有它们,正则表达式将适用于任何至少具有类似空格字符的字符串)
回答by René Baudisch
How about NOTchecking "word" by RegExp but using RegExp to replace all whitespaces and look what's left. If it's empty "word" is only composed by whitespaces:
如何不通过 RegExp 检查“单词”,而是使用 RegExp 替换所有空格并查看剩下的内容。如果它是空的“单词”仅由空格组成:
if (word.replace(/\s+/, "") === "") {
console && console.log("empty string found!");
return 'no name';
}