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

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

The structure is as follows:

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

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

+54
jquery contains replace text
Jul 04 2018-12-12T00:
source share
4 answers

You can use the text method and pass a function that returns the changed text using your own String.prototype.replace to do the replacement:

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

Here is a working example .

+96
Jul 04 '12 at 7:45
source share
 var d = $('.text_div'); d.text(d.text().trim().replace(/contains/i, "hello everyone")); 
+8
Jul 04 '12 at 7:45
source share

If possible, you can wrap the word (s) that you want to replace in the span tag, for example:

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

Then you can easily change its contents using jQuery:

 $('.text_div > span').text('hello everyone'); 

If you cannot wrap it in a span tag, you can use regular expressions.

+4
Jul 04 2018-12-12T00:
source share

You can use contains selector to search for elements containing specific text.

 var elem = $('div.text_div:contains("This div contains some text")')​; elem.text(elem.text().replace("contains", "Hello everyone")); 

+3
Jul 04 2018-12-12T00:
source share



All Articles