A question about Remove Whitespace from Start and End

Hi, sorry if I’m doing this wrong this is the first time I’m asking a question here. Anyways i passed the challenge but I’m not satisfied with the solution I came up with and was wondering if anyone can tell me some pro’s or con’s about this:

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

//log result 
Hello, World!

I did look at the solution given and I get what it does just curious about the possibilities.

Link to the Challenge
Remove Whitespace from Start and End

hi there, which challenge is this supposed to be about? Please post a link to it.

oh sorry i forgot about the link
Remove Whitespace from Start and End

The problem I see here is that you are not really trimming the whitespace around a string. You are just replacing the matched string with “Hello, World!” so that is not really a solution (what happens if the variable hello has a different string for eg).
Your pattern isn’t doing anything useful in the current code because you could have written it as /.*/ and that would also have worked (again because you are not doing anything with the match you are just replacing the entire thing).

What you want to do instead is use a pattern that makes use of capture groups.
And then use that capture group in the replace line.

Yes, I agree the coding isn’t really doing anything useful. It’s just replacing the entire string, I was just wondering why the solution given didn’t make use of capture group as well. But settled with the OR | operator and how would capture be used here when there isn’t a literal string to replace it with. Seeing as how in the previous challenges we used the Dollar sign $ inside a variable which contained the capture group order or it can be used without it ?

I haven’t looked at the solutions for this step (I never do if I can solve them myself).
I used a capture group to solve this one in a way where it didn’t matter which string was used in between the front and back spaces.
You can look up how to use capture groups with the replace function in javascript to find out more online. (I’m sorry I can’t share my solution with you)

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