最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex only spaces - javascript - Stack Overflow

programmeradmin0浏览0评论

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!

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!

Share Improve this question edited Aug 16, 2016 at 14:01 Dylan Meeus 5,8023 gold badges32 silver badges49 bronze badges asked Jun 24, 2011 at 17:46 MarcoMarco 611 gold badge1 silver badge2 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 14

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)

Just use the space character instead of the \s.

'   '.match(/ +/)
''.match(/ +/)

Output

["   ", index: 0, input: "   ", groups: undefined]'
null

You could do this same check with !word.trim() as well, and ignore regex completely.

How about NOT checking "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:

   if (word.replace(/\s+/, "") === "") {
      console && console.log("empty string found!");
      return 'no name';
   }
发布评论

评论列表(0)

  1. 暂无评论