从这个正则表达式,
text.replace(/^\s+|\s+$/g,"").replace(/ +/g,' ')
如何删除仅用于尾随空格的正则表达式?
我是正则表达式的新手并做了一些研究,但我无法理解这种模式。
从这个正则表达式,
text.replace(/^\s+|\s+$/g,"").replace(/ +/g,' ')
如何删除仅用于尾随空格的正则表达式?
我是正则表达式的新手并做了一些研究,但我无法理解这种模式。
/^\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直到找不到匹配为止。
因此,如果要删除匹配字符串末尾的空白字符的部分,请删除该|\s+$部分(以及g标志,因为^\s+无论如何只能在一个位置匹配 - 在字符串的开头)。
学习正则表达式的有用资源: