我想用“W3Schools Test$”替换字符串“Microsoft”。
请注意美元符号后有单引号。
它不适用于我的以下代码。您可以看到演示一运行良好,但演示二运行不佳。
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>
这是上面代码的输出。
单击按钮将下面段落中的“Microsoft”替换为“W3Schools”:
访问 W3Schools 测试 $!
访问 W3Schools 测试!!
第三行应该显示为 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/