I am lost about how this works:
x=x.replace(/^\s+|\s+$/g,"");
What is the pipe( | ) for ?
The pipe means "or".
So your regex matches
^ # the start of the string
/s+ # followed by whitespace (one or more characters)
| # or
/s+ # whitespace
$ # followed by the end of the string
The /g (global) modifier applies the regex to all matches in the string, not just the first one.
g, the / is part of the delimiter which indicates the end of the regular expression.It means or. The part to the left matches any leading spaces (^), the part to the right matches any trailing space ($). The g modifier allows this matching to be applied more than once, which is useful if you're expecting both trailing and leading space.
Basically this regex trims whitespace.
An alternative way to write this regex is, using the new RegExp construct:
x = x.replace(new RegExp("^\s+|\s+$", "g"), "");
If find this notation more readable because you don't need your delimiters (/) and your modifier is separated.
It's an alternation construct.
The regex says "either the beginning-of-string followed by one or more whitespace characters, OR, one or more whitespace characters followed by end-of-string".
I think that is the intent, anyway. I'm not sure now that I read JaredPar's answer.
If I were writing this I would use parens to make it explicit.
x = x.replace(/(^\s+|\s+$)/g,"");
^ and $ match the end of the string, not the end of the line, unless the /m modifier is used, which it isn't.Pipe is represent OR
/g represents Global
\s represents Space
\s means "whitespace character" (which includes standard space, tab, carriage return, line feed, and more obscure ones as well)
/gpart?