Replace a particular string of an element in jQuery
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.
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'); $("#myText").html(modifiedText);
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.
- How to check if an HTML element is loaded or not using jQuery
- How to change CSS property on click in jQuery?
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.