我想将字符串“ Microsoft”替换为“ W3Schools Test $”。

请注意,美元符号后有单引号。

它不适用于我的以下代码。您可以看到演示1正常运行,但是在演示2的情况下效果不佳。



function myFunction() {
    var str_one = document.getElementById("demo-one").innerHTML;
    var res_one = str_one.replace("Microsoft", "W3Schools Test$");
    document.getElementById("demo-one").innerHTML = res_one;

    var str_two = document.getElementById("demo-two").innerHTML;
    var res_two = str_two.replace("Microsoft", "W3Schools Test$'");
    document.getElementById("demo-two").innerHTML = res_two;
}

<p>Click the button to replace "Microsoft" with "W3Schools" in the paragraph below:</p>

<p id="demo-one">Visit Microsoft!</p>
<p id="demo-two">Visit Microsoft!</p>

<button onclick="myFunction()">Try it</button>





这是上面代码的输出。

Click the button to replace "Microsoft" with "W3Schools" in the paragraph below:Visit W3Schools Test$!Visit W3Schools Test!!

第三行应显示为Visit W3Schools Test$',但应显示为Visit W3Schools Test!!

请帮助我摆脱这个问题。

提前致谢。

最佳答案

replace的上下文中,$'用于插入匹配的子字符串之后的字符串部分。

要使用$插入string#replace,请使用$$



function myFunction() {
    var str_one = document.getElementById("demo-one").innerHTML;
    var res_one = str_one.replace("Microsoft", "W3Schools Test$");
    document.getElementById("demo-one").innerHTML = res_one;

    var str_two = document.getElementById("demo-two").innerHTML;
    var res_two = str_two.replace("Microsoft", "W3Schools Test$$'");
    console.log(res_two);
    document.getElementById("demo-two").innerHTML = res_two;
}

<p>Click the button to replace "Microsoft" with "W3Schools" in the paragraph below:</p>

<p id="demo-one">Visit Microsoft!</p>
<p id="demo-two">Visit Microsoft!</p>

<button onclick="myFunction()">Try it</button>

关于javascript - 将字符串“Microsoft”替换为“W3Schools Test $'”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46945532/

10-11 07:00