Regular Expressions: Remove Whitespace from Start and End

Hello everyone. I have been trying the following code so far to solve this challenge:

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

I have tried it also on jsbin.com and the result is “Hello, World!”, as expected. But on freeCodeCamp I pass two out of the three tests but the third says:
result should equal to “Hello, World!”. What am I doing wrong?
Thank you in advance.

When you have problem with a challenge to provide a link to it will improve the pertinence of the answers :slight_smile:

Anyway, you’re testing for spaces at the start OR spaces at the end ^^
If you want the regex not to match just the first occurrence ( the spaces at the start i guess) you should use the g flag ^^

4 Likes

Wow thank you so much. That solved it.

1 Like

After few tries, I looked in the solution https://guide.freecodecamp.org/certifications/javascript-algorithms-and-data-structures/regular-expressions/remove-whitespace-from-start-and-end/ but solution mentioned here doesn’t work

let wsRegex = /^\s+|\s+$/g; // Change this line

Per my understanding

  1. caret symbol ^ looks at the start of string
  2. dollar symbol $ looks at the end of string
  3. didn’t understand what the purpose of | ?
  4. \s+ looks for one or more white spaces then why global flag g is needed ?

How did you solve the problem ?

The | is an OR operator
The g flag is needed to match all the spaces that are at the beginning OR at the end. Otherwise it would match only the first part of the regex, and the second part only if the first part doesn’t match anything

Thanks for clarification but I found official solution given doesn’t work. One of tests

result should equal to `“Hello, World!”

fails, what may be going wrong with FCC editor ?

Post your code please

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