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
meansThe
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 theg
flag since^\s+
can only match at one position anyway - at the beginning of the string).Useful resources to learn regular expressions: