Why dosen't this work /^(\s+)$/ at all? - Challenge: Remove Whitespace from Start to End

Im curious as to why this regex dosen’t work, it feels like it should.

let wsRegex = /^(\s+)$/g;
let result = hello.replace(wsRegex, “”);
console.log(result);
//returns " Hello, World! "

im trying to get it to search the beginning and the end. i’d kind of expect it to have gotten at least the first side as /^(\s+)/g does - trying to avoid the alternator as i dont really understand why its necessary and think understanding this solves both my problems. Thanks.


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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36.

Challenge: Remove Whitespace from Start and End

Link to the challenge:

I think your code does not specify the whitespace for both starting and ending seperately.

^(\s+)$ will only match a line that contains only space characters.

You can use this great site called RegExr to test your regexes, and see where they are going wrong.

Check out the example RegExr pattern I saved for you by clicking here

As you can see, it doesn’t match your string. The way your regex is currently worded, you are asking for a string that starts with a space character and consists only of space characters till the very end.

I think a great solution would be

/^(\s+)|(\s+)$/g

Which looks for spaces at the beginning and end of a given string, regardless of what’s between them.

You can see it in action here

It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.

We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions.

Thank you for understanding.

Try this,

Let hello=" hello World. "
Let regex=/\s+/g;
Let result=hello.replace(regex,"")
Console.log(result)

But the easiest way is;
console.log(hello.trim())
Hope this helps

Or try this,
/^\s+|(\s+)$/

with that you are going to remove also the space between the words, so it is not the solution

also the point of the challenge is to solve it with regex, so not using trim

1 Like

that makes a lot of sense thank you-

the code i posted is an accidental regex for whitespace from start to end.

1 Like