jQuery if div contains this text, replace that part of the text

Daniel picture Daniel · Jul 4, 2012 · Viewed 236.8k times · Source

Like the title says, I want to replace a specific part of the text in a div.

The structure looks like this:

<div class="text_div">
    This div contains some text.
</div>

And I want to replace only "contains" with "hello everyone", for example. I can't find a solution for this.

Answer

James Allardice picture James Allardice · Jul 4, 2012

You can use the text method and pass a function that returns the modified text, using the native String.prototype.replace method to perform the replacement:

​$(".text_div").text(function () {
    return $(this).text().replace("contains", "hello everyone"); 
});​​​​​

Here's a working example.