Javascript:正则表达式替换两个字符及其周围的所有空格

标签 javascript regex string

我有一个字符串,想用“<”和“>”替换两个字符“<”和“">”的所有实例及其周围的所有空白(没有制表符,没有换行符,可能为空),分别。

Can I do this with a one-liner replace regex expression?

缓慢而艰难的方法是

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(">"," > ");

缩短空白的说明见 Regex to replace multiple spaces with a single space ,但我不假设这两个字符周围有空格。

我的用例是将数学表达式保存在数据库中,以便使用 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 flag表示进行全局替换,而不是仅仅替换第一个匹配项,括号是创建一个捕获组,以便我们可以使用 $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);

关于Javascript:正则表达式替换两个字符及其周围的所有空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47388476/

相关文章:

javascript - 无法在 Windows 7 中运行全局安装的 Node 模块

javascript - iPad/iPhone 预加载图像时出错

java - Android java的正则表达式提取数字和特定符号

c++ - 正则表达式迭代器在 Cpp 中不起作用

javascript - 如何中断动画

javascript - 在vue js中使用v-for在div内创建组件

python - 使用 findall() 方法解析简单的数学方程

java - Java 中 PHP 的 gzuncompress 函数?

java - 使用替换第一方法替换字符串

java - 创建字符串数组的链表