Remove whitespaces start and end challenge

so I have finished the challenge, I looked at the solution to check how it was done, and I have a question.


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

I understand the regex, but the result where it removes all empty strings didn’t it remove the one at Hello, World as well? the one after the comma.
Thanks!

Your code so far


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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36

Challenge: Remove Whitespace from Start and End

Link to the challenge:

/^\s+|\s+$/

Notice those extra characters at the beginning and end of the pattern (^ and $). Do you know what those do?

1 Like

yes ofcourse, ^ searches for a pattern in the beginning, $ searches for a pattern in the end.

But I still don’t understand why the space after the comma ain’t removed too.

You just answered your own question :slight_smile: Those are anchors, they anchor the search to the beginning of the string and the end of the string. Is the space between the words at the beginning or end of the string?

Okay, but does the replace() ignore flags?

The replace() will respect whatever flags you have on the pattern. I’m assuming you are referring to the g flag being used here? Why do you think it is being used? If you are not sure, a good site to test patterns is regular expressions 101. Test the pattern with and without the g flag and see what happens.