使用javascript将单词替换成另一个单词

问题描述 投票:0回答:1

我有以下代码。我试图将所有hello的实例改为hey。我创建了一个变量text来存储这个字符串。然后我试着在该字符串上使用replace方法,但它没有改变该字符串。我希望文本在 <p> 元素标签要改成 嘿嘿嘿嘿但它没有改变。我到底做错了什么?

HTML:

<p id="1">hello hello hello hello</p>

Javascript:

var text = document.getElementById("1").textContent;
text = text.replace(/hello/g,"hey");
javascript html
1个回答
0
投票

你可以像这样做。

为什么不工作

  1. 对于第一次通话 text= elem.textContent 其读取的值。
  2. 在第二次设置 text=replace 因为文本中只有字符串,所以不可能出现。p elem不是DOM elem

var text = document.getElementById("1").textContent;
console.log(text) //direct string
text = text.replace(/hello/g, "hey")
<p id="1">hello hello hello hello</p>

解决办法

var text = document.getElementById("1");
console.log(text) //dom element 
text.textContent = text.textContent.replace(/hello/g, "hey")
<p id="1">hello hello hello hello</p>
© www.soinside.com 2019 - 2024. All rights reserved.