Replace a particular string of an element in jQuery

In this post, we are going to learn how we can replace a particular string of an element in jQuery. We are going to understand it with simple and easy jQuery JavaScript code snippet.

Let’s see how we can do it with the example because an example is the best way to understand anything.

First of all, let’s create our paragraph tag with an ID in HTML:

<p id="myText">The child loves chocolate.</p>

The ID will be used to get the content from our paragraph tag element. We will then use the content and replace certain string and then return inside the element again.

After that, we just have to write our jQuery JavaScript code to make it work.

Below is our jQuery code that will replace the string “chocolate” into “ice cream”:

var originalText = $("#myText").html();
var modifiedText = originalText.replace('chocolate', 'ice cream');


Now let’s see a little bit if description about our jQuery code.

In our jQuery code, we have first taken out paragraph content by its ID using the jQuery html() method. After that, we take another variable where we store the modified text where we have replaced the original text which is the content of our paragraph tag.

Also, read:


Now the main trick is here. We have used the JavaScript replace method to replace the particular string of our content.

Below is the syntax of JavaScript replace() method:

string.replace(searchstring, newstring)

Below is the value of the parameters of the syntax:

searchstring: Our string that we want to replace.

newstring: Our new string that will replace the old.

Finally, we have taken the final modified text and put it inside the paragraph using jQuery html() method.

That’s it. We did it. now you can test the code on your browser. Remember to link jQuery file before the jQuery code on the page.

If everything goes right, you should see “ice cream” instead of “chocolate” inside the paragraph.

So we successfully replace a particular string of an element in jQuery.


Leave a Reply

Your email address will not be published. Required fields are marked *