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

时间:2021-04-18 02:56:28

标签: javascript html dom attributes getelementsbyclassname

假设我有一个输入元素:

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

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

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

但是如果我想将“example”替换为“example2”,这可能吗?我尝试过使用诸如 replace() 之类的常见 HTML DOM 关键字,但无济于事。这甚至可能吗?

1 个答案:

答案 0 :(得分:1)

你可以试试.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>

相关问题