Can't understand the difference between + and g flag

The

let reCriminals = /C+/; 

and

let reCriminals = /C+/g; 

have the same output. What is the difference?

The g flag will match more than the first occurrence of the regex’s match. Without the g flag, only the first occurrence is found.

const regex1 = /C+/;
const regex2 = /C+/g;

const string = 'abCCCdeCffghCCCzz';

const matchOfRegex1 = string.match(regex1);
const matchOfRegex2 = string.match(regex2);

console.log(matchOfRegex1); // [ 'CCC', index: 2, input: 'abCCCdeCffghCCCzz', groups: undefined ]
console.log(matchOfRegex2); // [ 'CCC', 'C', 'CCC' ]
2 Likes

Hello!

Let’s take the string CC something something CC something CC.

The first regex (/C+/) would match only the first CC:

image

The second one would search the entire string, matching every occurrence of CC:

image

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.