我想用“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!!
请帮助我摆脱这个问题。
提前致谢。
答案 0 :(得分:4)
在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;
}
&#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;
答案 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;
}