我尝试替换以下HTML中的heelo|paul
,并将其替换为/heelo to paul/
<p>Dear sir {{heelo|Paul}} ,</p>\n<p>I'm just testing please wait</p>\n<p>yours faithfully,</p>\n<p>
这是我使用的正则表达式:
str.replace(/.*?{{|}}/g, "/$1 to $2/")
但它会产生错误的结果:
<p>Dear sir /$1 to $2/heelo|Paul/$1 to $2/ ,</p>\n<p>I'm just testing please wait</p>\n<p>yours faithfully,</p>\n<p> 
有什么想法吗?
答案 0 :(得分:2)
我认为这就是你要找的......
var p = document.getElementById('greetings');
p.innerText = p.innerText.replace(/.*?\{\{([\w\s]+)\|([\w\s]+)\}\}/, "/$1 to $2/");
&#13;
<p id="greetings">Dear sir {{heelo|Paul}} ,</p>\n<p>I'm just testing please wait</p>\n<p>yours faithfully,</p>\n<p>
&#13;
答案 1 :(得分:2)
您忘记了|
与\
一起逃脱,并且还将组添加到您想要的匹配项中。试试这个正则表达式:
(.*?{{)(.*?)\|(.*?)(?=}})
这是一个有效的Javascript:
var myString = "<p>Dear sir {{heelo|Paul}} ,</p>\n<p>I'm just testing please wait</p>\n<p>yours faithfully,</p>\n<p> ";
document.write(myString.replace(/(.*?{{)(.*?)\|(.*?)(?=}})/g, "$1/$2 to $3/"));
&#13;