regex remove white space after text [duplicate]

2019-09-07 15:26发布

This question already has an answer here:

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.

1条回答
【Aperson】
2楼-- · 2019-09-07 15:57

/^\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:

查看更多
登录 后发表回答