Search code examples
javascripthtmldomattributesgetelementsbyclassname

Replace certain values in String with another


Let's say I had an input element:

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

And I wanted to set the value (which inserts text in the input element):

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

But if I wanted to replace "example" with, let's say, "example2", would that be possible? I've tried experimenting with common HTML DOM keywords such as replace(), to no avail. Is this even possible at all?


Solution

  • You can try .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>

    Unfortunately, in the example above, example2 would become example22. If you don't want this behavior, try the following:

    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>