我正在尝试替换以下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> 
有什么想法吗?
您忘记了使用 转义
|
,也忘记将组添加到您想要的匹配项中。试试这个正则表达式:
(.*?{{)(.*?)|(.*?)(?=}})
这是一个有效的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/"));
我认为这就是你要找的...
var p = document.getElementById('greetings');
p.innerText = p.innerText.replace(/.*?{{([ws]+)|([ws]+)}}/, "/$1 to $2/");
<p id="greetings">Dear sir {{heelo|Paul}} ,</p>n<p>I'm just testing please wait</p>n<p>yours faithfully,</p>n<p>