是我的语法正确我想替换模式abcd + abcd +中的字符串但是它在JavaScript中使用replace方法不起作用是代码快照 评论的一剂不起作用我需要
function myFunction() {
var str = document.getElementById("demo").innerText;
//var res = str.replace(/+/g, "red");
var res2 = str.replace("+", "red");
document.getElementById("demo").innerText = res2;
}
<p>Click the button to replace "blue" with "red" in the paragraph below:</p>
<p id="demo">Mr + has a + house and a blue car.</p>
<button onclick="myFunction()">Try it</button>
答案 0 :(得分:2)
注释掉的部分几乎是正确的,但你需要逃避+
,因为它是正则表达式中的特殊字符:
function myFunction() {
var str = document.getElementById("demo").textContent;
var res = str.replace(/\+/g, "red");
document.getElementById("demo").textContent= res;
}
<p>Click the button to replace "blue" with "red" in the paragraph below:</p>
<p id="demo">Mr + has a + house and a blue car.</p>
<button onclick="myFunction()">Try it</button>
innerText
是IE推出的一种古怪的非标准属性。强烈建议改为使用标准,更快,更可靠的textContent
- 请参阅http://perfectionkills.com/the-poor-misunderstood-innerText