You must use parentheses () to indicate that you want to combine either the left or right side of the "|" character, not square brackets. The square brackets actually correspond to character sets (ie [Grapes] will correspond to a single instance of "g", "r", "a", "p", "e" or "s", whereas (grapes | apples ) will correspond to "grapes" or "apples").
In addition, another thing that you are missing is the indication of quantity. In other words, once you match a space (\ s), how many places should it look for? In your example, this matches only one space. You probably want to combine as many consecutive spaces as there are left and right of the line. To do this, you need to add * (a match of zero or more) or + (a match of one or more) immediately after the \ s character.
So, to rewrite your regex:
var input = " first second "; var trimmed = input.replace(/(^\s+|\s+$)/g, ''); console.log(trimmed);
You can copy and paste these lines into the JavaScript console to see that you get the desired result. In this regular expression, the regular expression "matches one or more space characters from the beginning of a line or one or more space characters, followed by the end of a line." Then, the replace function accepts this correspondence and replaces it with ".".
source share