Skip to content

jQuery string replace all

  • by

In jQuery, you can use the replace() method along with a regular expression to replace all occurrences of a string in a given text.

By using the global g flag in the regular expression, you can match all occurrences of the pattern in the text. The replace() method returns a new string with all occurrences of the pattern replaced with the specified replacement string.

Here is an example code snippet that replaces all occurrences of the string “apple” with “orange” in a given string:

var str = "I have an apple, he has an apple too";
var newStr = str.replace(/apple/g, "orange");

console.log(newStr); // "I have an orange, he has an orange too"

In the above code, the regular expression /apple/g is used to match all occurrences of the string “apple” in the str variable. The g flag is used to perform a global search, meaning all occurrences of the pattern will be matched and replaced.

jQuery string replaces all example

A simple example code demonstrates how to use jQuery to replace all occurrences of a string:

<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function() {
      var originalString = "The quick brown fox jumps over the lazy dog.";
      var newString = originalString.replace(/the/gi, "a");
      console.log(newString);
    });
  </script>
</head>
</html>

Output:

jQuery string replace all

Another example

Let’s say you have a web page where users can leave comments, and you want to replace all occurrences of a specific word in those comments.

<!DOCTYPE html>
<html>
<head>
  <title>Comment Example</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function() {
      // Get all comments on the page
      var comments = $(".comment");

      // Loop through each comment and replace the word "bad" with "good"
      comments.each(function() {
        var commentText = $(this).text();
        var newCommentText = commentText.replace(/bad/g, "good");
        $(this).text(newCommentText);
      });
    });
  </script>
</head>
<body>
  <h1>Comments</h1>
  <div class="comment">I thought this movie was bad.</div>
  <div class="comment">The service at this restaurant was bad.</div>
  <div class="comment">I had a bad experience with this product.</div>
</body>
</html>

In this example, any comments on the page that contain the word “bad” will be updated to use the word “good” instead.

Comment if you have any doubts or suggestions on this jQuery string topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading