Invert Regular Expression Matches with JavaScript- Plus sign

Invert Regular Expression Matches with JavaScript- Plus sign
0.0 0

#1

Tell us what’s happening:

why do I need to do a plus sign in /\s+/g; but if I do a plus sign with the capital S it gives me a wrong answer and I need to delete the plus?

I thought the plus meant that it shouldn’t stop at the first counted variable, I don’t understand :frowning:

Your code so far

// Setup
var testString = "How many non-space characters are there in this sentence?";

// Only change code below this line.

var expression = /\S/g;  // Change this line

// Only change code above this line

// This code counts the matches of expression in testString
var nonSpaceCount = testString.match(expression).length;

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36.

Link to the challenge:


#2

The difference between \s and \S is that the former matches all the whitespace while the latter matches all nonwhitespace.

The addition of + says to the regex engine - “I want 1 or more of the previous symbol”

Matches involving + are said to be greedy and take as many characters as they can in a given match.

so \s+ says match if there’s one or more whitespace in a row, making the longest match you can each time.

and \S+ says match if there’s one or more nonwhitespace in a row, making the longest match you can each time.

The latter then matches every word rather than every letter in the testcase, and the number of matches due to the greediness is lower.

Does this help?


#3

Oooh I get it now. Thank you very much.