Detect 2 spaces in whole string(sentence) with regex JS

Viewed 64

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?

3 Answers

Note that \s can also match a newline.

An option could be matching 2 times from the start of the string as least as possible chars followed by a whitespace char without a newline.

^.*?[^\S\r\n].*?[^\S\r\n]
  • ^ Start of string
  • .*? Match as least as possible chars
  • [^\S\r\n] Match a whitespace without a newline using negated character class [^
  • .*? Match as least as possible chars
  • [^\S\r\n] Match a whitespace without a newline

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

You might also for example match all whitespace chars using \s and then check if the number of matches is greater than 1.

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

Try the following regex:

.*\s.*\s.*

The .* matches 0 or more characters (any of them).

"More than one" can be rephrased as "at least two":

^(?:\S*\s){2}    // any two whitespace chars
^(?:[^ ]* ){2}   // any two regular space chars

You may change 2 with any other number to require at least X space/whitesapce chars.

See the regex demo.

Details:

  • ^ - start of string
  • (?: - start of a non-capturing group:
    • \S* - zero or more non-whitespace chars
    • \s - a whitespace char
  • ){2} - end of the group, repeat twice.

See a JavaScript demo:

["one space", "two or more spaces inside"].forEach(x =>
  console.log(x, '=>', /^(?:\S*\s){2}/.test(x))
)

Related