Search code examples
javascriptreplaceonchange

Find and replace using regex and a single input


I am trying to do a simple word changer. For this using a textarea, text and button. I will paste text in the textarea, for example type /red/g,'green' to textbox and click the button but something wrong and I don't know what it is. I'm new thanks for help.

function GetResult() {
  var text = document.getElementById('string-text').value;
  var letter = document.getElementById('string-letter');
  text = text.replace(letter);
}
<textarea id="string-text"></textarea>
<br><br>

<input id="string-letter" type="text">
<br><br>

<button id="string-btn" onclick="GetResult();">Change!</button>

I got what I want thank you.


Solution

  • You're trying to use a regular expression-alike string, and a replacement value after a comma.
    You could use:

    // Cache your static elements first
    const elText = document.querySelector('#text');
    const elReplacement = document.querySelector('#replacement');
    const elApply = document.querySelector('#apply');
    
    elApply.addEventListener("click", () => {
      const find = elReplacement.value.trim();
      
      if (!find) return; // Nothing to replace. End function here.
      const [full, match, flags, value] = find.match(/^\/?([^/]+)\/?([gmiyusd]+)?,(.+)$/);
      
      elText.value = elText.value.replace(new RegExp(match, flags), value);
    });
    <textarea id="text">Some text with red and multiple red!</textarea><br>
    Replace pattern:<br>
    <input id="replacement" type="text" placeholder="Your pattern" value="/red/g,green"><br>
    <button type="button" id="apply">Apply</button>

    PS:
    your UI would be better rewritten using some "Find:" and "Replace with:" input fields, than the above.