Regex lookaheads doubt

Hello, I have encountered a weird problem I want to understand.
So, the task was that I had to take the string " Hello, World! " and erase all whitespaces using the .replace () method.
My idea was to create a regex that looked for a string that started and ended with whitespaces, but that had something in the middle. So what I did was:

let hello = " Hello, World! "; // There are whitespaces on both sides
let wsRegex = /^\s+(?=.*)\s+$/g; // I had to change this line
let result = hello.replace(wsRegex, “”);

This way, I thought, I would find the string but would only match the whitespaces, and that way I would be able to erase only the whitespaces.
The thing is, wsRegex just wouldn’t match hello. So I decided to change wsRegex

let wsRegex = /^\s+(?=.)|(?=.)\s+$/g;

And it worked! But I don’t understand why; I feel like the logic is the same in both cases (in the first one, I look for a string that starts and ends by whitespaces, in the second one, I looked for strings that either started or finished by whitespaces. I feel like the hello variable matched both cases. I would really appreciate that someone clarifies my problem because I’m afraid of not quite understanding something important about how regEx works.

Erase every bit of white space in the string, or just any white space that occurs at the very beginning and end of the string?

Just at the end and the beginning

Lookaheads don’t actually match anything, they just verify that a pattern exists, so you can’t use it here if you are trying to capture part of the string (i.e. the string between the opening white space and the closing white space). And lookaheads are not necessary to solve this problem anyway.

You can use this approach, but you need to make two changes.

  • You need to change to stuff in the parens so it actually captures the string.
  • You need to change the second parameter to replace so that it replaces the string with the string you captured.

The lookaheads here are basically not doing anything, you don’t need them. The reason this works is because the regex is looking for either white space at the very beginning OR white space at the very end and since you are using the global (g) flag then it will match both of those in one shot.

1 Like

Yeah! I actually didn’t want to capture all that part of the string, so that was intentional; I just wanted to make sure there was something between those two white spaces.

Lol, it seems I overcomplicated things for no particular reason.

Thanks for the answer!

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