首页 > 解决方案 > Detect 2 spaces in whole string(sentence) with regex JS

问题描述

I need to detect if the sentence has more than ONE space: "one space" => false "two or more spaces inside" => true

I have such regex /\s\s+/g but it doesn't seem correct as it detects two spaces in a row but not in the whole provided string. How can I find more then ONE space in WHOLE string?

标签: javascriptregex

解决方案


注意也\s可以匹配换行符。

一个选项可以从字符串的开头匹配 2 次,尽可能少的字符,然后是一个没有换行符的空白字符。

^.*?[^\S\r\n].*?[^\S\r\n]
  • ^字符串的开始
  • .*?匹配尽可能少的字符
  • [^\S\r\n]使用否定字符类匹配没有换行符的空格 [^
  • .*?匹配尽可能少的字符
  • [^\S\r\n]匹配没有换行符的空格

[" a b", "a b ", " aa ", "    b", " a", "b "]
.forEach(s => console.log(`"${s}" --> ${/^.*?[^\S\r\n].*?[^\S\r\n]/.test(s)}`))

例如,您还可以使用匹配所有空白字符\s,然后检查匹配数是否大于 1。

[" a b", "a b ", " aa ", "    b", " a", "b "]
.forEach(s => console.log(`"${s}" --> ${s.match(/\s/g).length > 1}`))


推荐阅读