正则表达式删除文本后的空格 [英] regex remove white space after text
本文介绍了正则表达式删除文本后的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从这个正则表达式,
text.replace(/^\s+|\s+$/g,"").replace(/ +/g,' ')
如何删除仅用于尾随空格的正则表达式?
how do I remove the regex just for trailing white space?
我是 regex 的新手并做了一些研究,但我无法理解模式.
I am new to regex and did some research but I'm not able to understand the pattern.
推荐答案
/^\s+|\s+$/g
表示
^ // 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
g
修饰符表示重复匹配直到不再匹配为止.
The g
modifier indicates to repeat the matching until no match is found anymore.
因此,如果您想删除字符串末尾匹配空白字符的部分,请删除 |\s+$
部分(以及 g
标志,因为 ^\s+
无论如何只能在一个位置匹配 - 在字符串的开头).
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/
- JavaScript 中的正则表达式(因为这似乎是 JavaScript).
- http://www.regular-expressions.info/
- Regex in JavaScript (since this seems to be JavaScript).
这篇关于正则表达式删除文本后的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文