skip to Main Content

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.

2

Answers


  1. To replace something you need to replace what and replace with:

    document.querySelector('textarea').value = document.body.innerHTML.trim();
    
    function GetResult() {
    
      const [text, what, to] = 'text what to'
        .split(' ')
        .map(id => document.getElementById(`string-${id}`).value);
    
      document.getElementById('string-text').value = text.replaceAll(what, to);
    
    }
    <textarea style="width:100%" rows="7" id="string-text"></textarea>
    <label>Replace what
    <input id="string-what" type="text" value="Replace">
    </label>
    <label>Replace to
    <input id="string-to" type="text" value="Change">
    </label>
    <br><br>
    
    <button id="string-btn" onclick="GetResult();">Change!</button>
    Login or Signup to reply.
  2. You’re trying to use a regular expression-alike string, and a replacement value after a comma.
    You could use:

    • String.prototype.match() (with this regular expression) to retrieve the desired parts (regex pattern, regex flags, and the replacement word)
    • new RegExp(match, flags) constructor as the first argument of .replace(regularExpression, replacementString)
    // 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search