Remove Whitespace from Start and End Global Flag Requirement

Hello,
I have been working on removing whitespace challenge and my code was same as the solution but global flag. I don’t understand why we need a global flag there as we get same string without a global flag I appreciate any help. Thank you for your time.

Please provide a link to the challenge and show us the code you’ve tried.

let hello = " Hello, World! ";

let wsRegex = /^(\s+)|(\s+)$/;

let result = hello.replace(wsRegex, “”);

console.log(result)

Do you get the same result? Try it with this test code:

console.log(result.length)
console.log('***' + result + '***')
1 Like

Thank you so it doesn’t remove the space in the end. But I don’t get why It doesn’t remove the string in the end as we already use $ for that.

The g flag:

The $ marker just asserts what the end of the line to be. It is saying that we want the end of our selection to be there. I’d recommend hopping on a site like regex 101 and messing around with it - I always do that when I have to build regex. Building regex is a pain and is weird (at least to me) but it is also incredibly powerful and elegant.

1 Like

I appreciate your help have a nice day, will check it.

1 Like

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