Remove whitespace Best Practice !?

hi everyone

if you could rate my solution for that challenge, could you consider it Best Practice or Less or More (Average) or Newbie??

here my solution:


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

It depends on your goals.

If you just need to remove whitespace from the beginning and end, you can use string.trim()

If you want to make sure that the only place your string has spaces is a single space after each comma, then yours works fine.

There are other things you might want to do that could be done with different regular expressions (with or without also using trim(). For instance, you might want to make sure that there is never more than one space in a row, or that there is always a space after a period (full stop), etc.

1 Like

thanks for your reply

i used to try this regex


"   Hello, World!   ".replace(/\s{2,}/g, "")

could you consider it Best Practice than the old one I used before?

Like I said, it depends on your goal. If all you were trying to do is remove the whitespace at the beginning and end, then no. It would be considered better to just use trim().

1 Like

aah okey i understand now, thanks a lot for your help :slight_smile:

Good job solving the challenge and thinking critcally about your approach. Happy coding!

1 Like