Confused between + and g flag in RegExp

Tell us what’s happening:
Hi guys. I think I don’t quite understand the difference between g flag and + operator. What am I doing in these two following cases? Thank you!

Your code so far


let sample = "Whitespace is important in separating words";
let countWhiteSpace = /\s/g; 
//returns [ ' ', ' ', ' ', ' ', ' ' ]
 

let sample = "Whitespace is important in separating words";
let countWhiteSpace = /\s+/; 
/*returns [ ' ',
  index: 10,
  input: 'Whitespace is important in separating words',
  groups: undefined ]*/



**Your browser information:**

User Agent is: <code>Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36</code>.

**Challenge:** Match Whitespace

**Link to the challenge:**
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/match-whitespace

Hello!

The first regex matches every single white space present in the entire string, possibly matching multiple times.

The second regex matches at least one consecutive space a single time, that’s why you get a single match in the result.

Check what they do visually here (be sure to select ECMAScript on the left side):

With Global Modifier

Without Global Modifier

1 Like