![](/img/trans.png)
[英]JavaScript replace using regex for all multiline space and other whitespace characters
[英]Javascript: Regex to replace two characters and all their surrounding whitespace
我有一个字符串,并且想分别用“ <”和“>”替换两个字符“ <”和“>”的所有实例及其所有周围的空格(没有制表符,没有换行符,可能为空)。
我可以使用单行替换正则表达式来做到这一点吗?
缓慢而艰难的方式是
while (entry.value.indexOf(" <") > -1) {
entry.value = entry.value.replace(" <","<");
}
while (entry.value.indexOf("< ") > -1) {
entry.value = entry.value.replace("< ","<");
}
while (entry.value.indexOf(" >") > -1) {
entry.value = entry.value.replace(" >",">");
}
while (entry.value.indexOf("> ") > -1) {
entry.value = entry.value.replace("> ",">");
}
entry.value = entry.value.replace("<"," < ").replace(">"," > ");
正则表达式中解释了缩短空格,用一个空格替换多个空格 ,但是我不认为两个字符之间的空格。
我的用例是将数学表达式保存在数据库中,以便使用MathJax呈现在网站上。 这样做会碰到这个问题,请参阅http://docs.mathjax.org/en/latest/tex.html#tex-and-latex-in-html-documents 。
典型的表达式是
"Let $i$ such that $i<j$..."
"Let $<I>$ be an ideal in..."
(后者甚至不会在普通文本模式下的预览中在此处呈现。)
在此处复制粘贴Wiktor的评论。 \\s
匹配任何空格字符, *
表示匹配0个或多个空格字符, [<>]
匹配任何<
或>
, g
标志表示进行全局替换,而不仅仅是替换第一个匹配项,并且括号为创建捕获组,以便我们可以使用$1
将匹配项作为替换字符串中的反向引用来引用。
请参阅下面的一些示例输入输出。
'<>' // => ' < > ' (two spaces between the carets)
'<\t\t\n\ \n<' // => ' < < ' (again two spaces)
'>a \t b< ' // => ' > a \t b < '
'a>\n b <c ' // => 'a > b < c '
a = 'fpo< \\n>\\naf ja\\tb<>\\t<><>asd\\npfi b.<< > >'; b = a.replace(/\\s*([<>])\\s*/g, ' $1 '); console.log(b);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.