[jquery] Jquery: Find Text and replace

<div id="id1">
 <p>
   apple
 </p>
 <p>
   ball
 </p>
 <p>
   cat
 </p>
 <p>
   dogsss
 </p>
</div>

How Do I change dogsss to dollsss using jquery?

This question is related to jquery

The answer is


Try This

$("#id1 p:contains('dogsss')").replaceWith("dollsss");

I was looking for something similar and I use code that Doug Owings posted, but my text had some br tags and the code was erasing it.

So I use this: ( Just note that I replaced .text() to .html() )

Text:

< p class = "textcontent" > 
     Here some text replace me 
     < br > here an other text
     < br > here is more text 
< /p>

JS:

$('.textcontent').each(function() {

   var text = $(this).html();
   $(this).html(text.replace('replace me', 'I love this text')); 

});

Also if you want to edit several text create an array:

var replacetext = {
    "Text 0": "New Text 0",
    "Text 1": "New Text 1",
    "Text 2": "New Text 2",
    "Text 3": "New Text 3",
    "Text 4": "New Text 4"
};

$.each(replacetext, function(txtorig, txtnew) {
    var text = $('#parentid').html();
    $('#parentid').html(text.replace(txtorig, txtnew)); 
});

More specific:

$("#id1 p:contains('dog')").text($("#id1 p:contains('dog')").text().replace('dog', 'doll'));

$('p:contains("dogsss")').text('dollsss');

Joanna Avalos answer is better, Just note that I replaced .text() to .html(), otherwise, some of the html elements inside that will be destroyed.


How to change multiple "dogsss" to "dollsss":

$('#id1 p').each(function() {
var text = $(this).text();
// Use global flag i.e. g in the regex to replace all occurrences
$(this).text(text.replace(/dog/g, 'doll'));
});

https://jsfiddle.net/ashjpb9w/


$("#id1 p:contains('dog')").html("doll");

that'll do it.

http://jsfiddle.net/pgDFQ/


try this,

$('#id1').html($('#id1').html().replace('dogsss','dollsss'));

working sample


Warning string.replace('string','new string') not replaced all character. You have to use regax replace.

For exp: I have a sting old string1, old string2, old string3 and want to replace old to new

Then i used.

    var test = 'old string1, old string2, old string3';

   //***** Wrong method **********
    test = test.replace('old', 'new'); // This  will replaced only first match not all
    Result: new string1, old string2, old string3

  //***** Right method **********
    test = test.replace(/([old])+/g, 'new'); // This  will replaced all match 
    Result: new string1, new string2, new string3

Change by id or class for each tag

$("#id <tag>:contains('Text want to replaced')").html("Text Want to replaced with");


$(".className <tag>:contains('Text want to replaced')").html("Text Want to replaced with");