Or operator in regular expression

The only thing about this solution that is confusing me is the use of the | “or” operator . I thought that the or operator would only take one or the other. So I assumed that in this particular lesson that it would only take the first set of white space or the second set of white space.

So, Regardless of the | or operator does it take both sets of white space because regular expressions are greedy?

Your code so far


let hello = "   Hello, World!  ";
let wsRegex = /^\s+|\s+$/g; // 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/84.0.4147.89 Safari/537.36.

Challenge: Remove Whitespace from Start and End

Link to the challenge:

Yes, that’s right. The /g flag makes it greedy so it looks for any matches on either condition.

If it were not greedy it’d return the first match for one or the other.

1 Like

thank you ! I really dont like to continue in the lessons if im not really understanding why something happened.

Also I was going to mention that my first try I was able to pass the test by defining a replaceText variable with no space and the text “Hello, World!” then plugging it and the regex into hello.replace(). But I felt that my solution wasn’t the intended approach so I wanted to try it again differently .

Again thank you very much !

1 Like