Explanation for solution needed

Hello, can somebody explain to me why do we need the global flag in the regular expression?

I have let wsRegex = /^\s+|\s+$/; but I don’t quite get why is the global flag necessary for this case.

Your explanation will be very much appreciated ^^


let hello = "   Hello, World!  ";
let wsRegex = /^\s+|\s+$/g; // Change this line
let result = hello.replace(wsRegex, ""); // Change this line

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Safari/605.1.15

Challenge: Remove Whitespace from Start and End

Link to the challenge:

The regex looks for spaces at the start of the string or spaces at the end of the string. Without the g modifier, it will return only one match, but we want to trim both the spaces at the start and spaces at the end. (without g , it will trim only the start)

Thanks for explaining but I am still a little bit confuse. How does the replace method works? Does it mean that it checks the first conditions in the regex and replace the spaces in from of the string with “” then checks the second condition and does the same to the spaces at the back of the string? Or like does multiple condition means it checks all conditions at the same time?

lets say you use hello.match(wsRegex), you will find that if you use /g, you will receive more than 1 result.

Replace basically loops through all the items returned by match and replaces them.

2 Likes

How exactly it works would be written in a documentation.
But basically, it will go through the string and check if the conditions specified in the RegEx-string apply. Because it’s an “or” condition, it might check both on every character or be optimized to only check the second if the first returns false or identify that the first condition is for the start and the second for the end (funfact: you could switch those for the same result) - and hence ignore the first one once it’s beyond the “starting spaces”.

How exactly it works is written somewhere in the RegEx library, but the point of using it is to not needing to know this in detail :wink:

Here is an example of replace easier to assimilate:

console.log('abacbab'.replace(/a/, 'A'))  //Abacbab
console.log('abacbab'.replace(/a/g, 'A')) //AbAcbAb

@Dev_TK @Jagaya @Sylvant thank you for your explainations, I now have a clearer idea of how it works :smiley:

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