Daniel Lundahl Daniel Lundahl - 4 months ago 16
jQuery Question

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

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

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.

Comments