Help Remove Whitespace from Start and End

Tell us what’s happening:
I want to remove whitespace by the regex /(^\s+)(.*)(\s+$)/,I thought $2 might be the part with whitespace removed from start and end
the start whitespace is removed but the end white space cannot be completely removed. there is one space left to $2 ,the second capture group. can somebody tell me why?

Your code so far

let hello = "   Hello, World!  ";
let wsRegex = /(^\s+)(.*)(\s+$)/; // Change this line
let result = hello.replace(wsRegex,'$2'); // 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/81.0.4044.9 Safari/537.36.

Challenge: Remove Whitespace from Start and End

Link to the challenge:

You are very close. Pattern matching by default is greedy, which means a pattern will match as much as it can (gobble up as many characters as it can). Your second parens eats any type of character and will theoretically eat all the way to the end of the string, but your third parens is stopping it. The battle is between the second and third parens as to when the second stops eating. The second parens gets to eat first, so it will win. The third parens eats a minimum one whitespace character, so that’s all it will take back from the second parens. So you need to tell your second parens to stop at the last non-whitespace character it sees. You just need to add one thing at the end of the second parens to do that.

1 Like

thank you!!!great explanation

I mean, how to stop at a specific character ?I’ve googled but all the answer tell me how to stop at first match, not the last match

it turns out that this might work:/^\s+(.*\S)/
then choose the first capture group.
but i think your solution will be different.

Nope, that is my solution as well. Just needed to add \S to that grouping.