I’m not sure why my solution doesn’t work. In my mind wsRegex begins at the beginning of the string, matches with anything that is not a whitespace, then it matches with anything that is a whitespace, then it matches with anything that is not whitespace and finally returns everything it matched with to result. I know the solution posted finds the whitespaces and replaces them with nothing. My idea for the solution was find everything that is not a whitespace and return that (except for whitespaces in the middle of the word).
Your code so far
let hello = " Hello, World! ";
let wsRegex = /^\S*\s*\S*$/g; // Change this line
let result = hello.match(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/103.0.0.0 Safari/537.36
Challenge: Regular Expressions - Remove Whitespace from Start and End
Ah I see, but why won’t it keep searching until it finds a non-whitespace character at the beginning? Is the string not evaluated in a left-right fashion?
Ah I see, thank you for clearing that up! Also is there a way to evaluate the whitespaces but not include them in the match? Like could I use a positive lookahead to evaluate white spaces at the beginning? That way my function won’t be stopped.
Yes, there is. But, if you are really at the beginning of regular expressions, I would recommend you to learn the basics. FreeCodeCamp is really a good platform to start fresh in coding.
In this case, what you want is to match a first non-whitespace character one or more times, match a whitespace character, and finally match a non-whitespace character one or more times.
Just try without the caret (^) and the dollar sign ($). Those are restricting you.
I tried let wsRegex = /(?=\s*)\S*\s\S*/g; and result = [ ’ ‘, ’ ‘, ’ Hello,’, ’ World!’, ’ ', ’ ’ ]. Why are there spaces at the beginning and the end if I’m not matching those?
Will do, thanks! I figured out why it wasn’t working. The positive lookahead only works after you have something that matched. At least thats what I found.
No confusion! Thanks for helping me! I didn’t know there was a lookbehind. That should do the trick . Talking through this with you has really helped me understand it more! Thx!