Doubt about regex

Only for curiosity, why when I do that:

let haStr = “Hazzzzah”;
let haRegex = /Haz{4,}ah/g; // Change this line
let result = haRegex.test(haStr);

for that question:

Change the regex haRegex to match the word "Hazzah" only when it has four or more letter z 's.

It did not work…

It won’t work, as you cannot assign regex as literal. You have to use new RegExp()

The problem is about “g”… But I don’t know exactly what…

I dumb, of course, you can assign regex as literal.
As far as I understand using global flag g is tricky. Try this:

const str = 'Hazzzzah';
const reWithG = /Haz{4,}ah/g;
const reNoG = /Haz{4,}ah/;

reWithG.test(str);
reNoG.test(str);

console.log(reWithG.lastIndex) // 8
console.log(reNoG.lastIndex) // 0

…so if you want to reuse reWithG you need to reWithG.lastIndex = 0, otherwise it will start looking from index 9.

Hope this will help

1 Like

The easiest way around is not to assign regex to variable:

/Haz{4,}ah/g.test(str);

//this will work every iteration
1 Like