Regular Expressions - Remove Whitespace from Start and End

Tell us what’s happening:
Why would/doesn’t “let wsRegex = /^\W+|\W+$/;” work in this case? It seems to fail the test for output string, but I don’t understand why?

Your code so far

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

Challenge: Regular Expressions - Remove Whitespace from Start and End

Link to the challenge:

This is a great website for debugging and testing regex:

If you put in your regex there you can see what it will return. That should help you pinpoint the problem with your current regex. \W is probably not selecting what you think.

1 Like

You can easily trim unnecessary whitespace from the start and the end of a string or the lines in a text file by doing a regex search-and-replace. Search for [1]+ and replace with nothing to delete leading whitespace (spaces and tabs). Search for [ \t]+$ to trim trailing whitespace.


  1. \t ↩︎

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.