用另一个替换字符串中的某些值

Replace certain values in String with another

假设我有一个输入元素:

<input class="example" id="example"></input>

我想设置值(在输入元素中插入文本):

document.getElementsByClassName("example")[0].value += 'example';

但是如果我想用“example2”替换“example”,这可能吗?我曾尝试使用常见的 HTML DOM 关键字(例如 replace())进行试验,但无济于事。这有可能吗?

你可以试试.replaceAll():

var textarea = document.getElementsByTagName("textarea")[0];
function go(){
  textarea.value = textarea.value.replaceAll("example", "example2");
}
<textarea style="width:100%">example example example2 example</textarea>
<br/>
<button onclick="go()">Replace all occurences of 'example' with 'example2'</button>

不幸的是,在上面的例子中,example2 会变成 example22。如果您不希望出现这种情况,请尝试以下操作:

var textarea = document.getElementsByTagName("textarea")[0];
function go(){
  split = textarea.value.split(" ");
  constructed = "";
  for(let i = 0; i < split.length; i++){
    if(split[i] == "example"){
      constructed+="example2 ";
    }else{
      constructed+=split[i]+" ";
    }
  }
  constructed = constructed.substring(0, constructed.length-1);
  textarea.value = constructed;
}
<textarea style="width:100%">example example example2 example</textarea>
<br/>
<button onclick="go()">Replace all occurences of 'example' with 'example2'</button>