Remove Whitespace from Start and En

Tell us what’s happening:
Hello there, I solved using this expression. Is this alright?? Or the one proposed is a better way and why??

Your code so far


let hello = "   Hello, World!  ";
let wsRegex = /[\s][\s$]+/g; // Change this line
let result = hello.replace(wsRegex, ""); // Change this line
console.log(result);
1 Like

I personally like your solution. …just something to be aware of as you go through these challenges, the suggested solution is only a solution (usually provided by a member of this community) and not necessarily the best solution.

Got it. I knew that they are provided by community, but I thought they choose the best way to do.

Not always. And now that you’re a member of this community, once you feel more comfortable, you can provide/update solutions too.

Your solution works for the provided string, but not for the reason you think. This regex:

let wsRegex = /[\s][\s$]+/g;

Matches anywhere in the string, one whitespace character, followed by one or more whitespace characters or a $ character (the $ loses its meaning inside a character class). This is enough to strip the double-whitespace around the sides of " Hello World " but would fail on " Hello World " with only one space on either side.

It’s most easily solved with two regex replacements: One that matches any amount of whitespace at the beginning, and one at the end.

3 Likes

So true, very good point!

Actually, I started with that mindset, "I need to remove blank spaces at the start and end of the string, first I tried with ^ and $, but it didn’t worked out as I expected, so I give some tries and I get that one.