正则表达式只有空格 - JavaScript

问题描述 投票:2回答:2

我需要过滤一个只由空格组成的字段;就像是:

if (word == /((\s)+)/ ) return 'no name'

但它不起作用......还有其他想法吗?谢谢你的想法!

javascript regex whitespace
2个回答
10
投票

你应该使用if(/^\s+$/.test(word))。 (注意^$,没有它们,正则表达式将保留任何至少具有类似空格的字符串)


-2
投票

如何不通过RegExp检查“单词”,而是使用RegExp替换所有空格并查看剩下的内容。如果它是空的“单词”只由空格组成:

   if (word.replace(/\s+/, "") === "") {
      console && console.log("empty string found!");
      return 'no name';
   }
© www.soinside.com 2019 - 2024. All rights reserved.