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

时间:2017-10-26 03:45:12

标签: javascript html

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

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

它不适用于我的以下代码。你可以看到demo-one工作正常,但是在demo-two的情况下效果不佳。

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!!

请帮助我摆脱这个问题。

提前致谢。

2 个答案:

答案 0 :(得分:4)

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

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

&#13;
&#13;
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;
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

TextView's drawableLeft
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;
    }