Why is the | needed in the following regex?
let hello = " Hello, World! ";
let wsRegex = /^\s+|\s+$/g; // Change this line
let result = hello.replace(wsRegex, ""); // Change this line
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/regular-expressions/remove-whitespace-from-start-and-end/
The | in a regex setting means
Match the leftside of the pipe or the rightside of the pipe.
Why is it doing both? Because of the g flag; after the first match, it attempts another one that satisfies the right side pattern. Since $ is the end of the string; there is nothing more to match.
the pipeline | serves as alternation which acts like boolean OR, why you need it is definitely because you need to match one or more white at the beginning hence the ^\s+ OR | one or more White spaces in the end.