jQuery - Replace all instances of a particular string in a textarea

← PrevNext →

Using jQuery replace() or replaceAll() method. These two jQuery inbuilt methods can be used to replace all instances of a particular string in a textarea. In my previous tutorial I have shared a similar example using plain JavaScript.

1) Using replace() method

In the first example, I am using the replace() method with RegEx (or regular expressions) to locate the string I want to change and replace it with a new string.

The Markup
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
  <div>
    <p>
        <textarea id="ta"></textarea>
    </p>
    <p>
        <input type="text" id="txt2replace" placeholder="enter the text to replace">
    </p>
    <p>
        <input type="text" id="replacewith" placeholder="enter the text to replace with">
    </p>
    
    <p>
      <input type="button" value="Click to Replace" id="bt">
    </p>    
  </div>
</body>
The Script
<script>
  $(document).ready(function () {
    $('#bt').click(function() {

      let t1 = $('#txt2replace').val();
      let t2 = $('#replacewith').val();
      
      // create a regexp object and do a "global" search of the string.
      const reg = new RegExp(t1, "g");	
      
      $('#ta').val(
        $('#ta').val().replace(reg, t2)	// replace with new string (or text)
      );
    });
  });
</script>
Try it

2) Using replaceAll() method

The markup remains the same like the above example.

<script>
  $(document).ready(function () {
    $('#bt').click(function() {

      let t1 = $('#txt2replace').val();
      let t2 = $('#replacewith').val();

      $('#ta').val(
        $('#ta').val().replaceAll(t1, t2)
      );
    });
  });
</script>
Try it

By the way, you can do this without using a framework. See this pure JavaScript example.

That's it. Happy coding. 🙂

← PreviousNext →