[英]regex only spaces - javascript
我需要過濾僅由空格組成的字段; 就像是:
if (word == /((\s)+)/ ) return 'no name'
但它不起作用......還有其他想法嗎? 謝謝你的想法
您應該使用if(/^\\s+$/.test(word))
。 (注意^
和$
,如果沒有它們,則正則表達式將保留至少具有空格字符的任何字符串)
只需使用space
字符而不是\s
。
' '.match(/ +/)
''.match(/ +/)
Output
[" ", index: 0, input: " ", groups: undefined]'
null
您也可以使用.word trim()
進行同樣的檢查,並完全忽略正則表達式。
如何不通過RegExp檢查“單詞”,而是使用RegExp替換所有空格並查看剩下的內容呢。 如果為空,則“ word”僅由空格組成:
if (word.replace(/\s+/, "") === "") {
console && console.log("empty string found!");
return 'no name';
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.