This question already has an answer here:
-
Trim string in JavaScript?
25 answers
From this regex,
text.replace(/^\s+|\s+$/g,"").replace(/ +/g,' ')
how do I remove the regex just for trailing white space?
I am new to regex and did some research but I'm not able to understand the pattern.
/^\s+|\s+$/g
means
^ // match the beginning of the string
\s+ // match one or more whitespace characters
| // OR if the previous expression does not match (i.e. alternation)
\s+ // match one or more whitespace characters
$ // match the end of the string
The g
modifier indicates to repeat the matching until no match is found anymore.
So if you want to remove the part the matches whitespace characters at the end of the string, remove the |\s+$
part (and the g
flag since ^\s+
can only match at one position anyway - at the beginning of the string).
Useful resources to learn regular expressions:
- http://www.regular-expressions.info/
- Regex in JavaScript (since this seems to be JavaScript).