Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery find text and replace (all)

<div id="id1">

   apple

   ball

   dogsss

   dogsssdogsss

   dogsssdogsssdogsss

</div>

How Do I change ALL dogsss to dollsss using jquery?

Here is a code, but how to determine the element?

$('#id1 how???').each(function() {
    var text = $(this).text();
    $(this).text(text.replace('dog', 'doll')); 
});

Here is similar question http://stackoverflow.com/questions/8146648/jquery-find-text-and-replace

like image 987
Arriba Avatar asked Nov 15 '25 09:11

Arriba


2 Answers

Your replace will only remove first occurrence from the string. Use regex with replace to remove all occurrences. Use global flag i.e. g in the regex to replace all occurrences.

Change

$(this).text(text.replace('dog', 'doll')); 

To

$(this).text(text.replace(/dog/g, 'doll')); 

Also, you can use text() with callback to update the innerText of element.

Demo

$('#id1').text(function(i, oldText) {
  return oldText.replace(/dog/g, 'doll');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div id="id1">

  apple ball dogsss dogsssdogsss dogsssdogsssdogsss

</div>
like image 87
Tushar Avatar answered Nov 18 '25 00:11

Tushar


You should use the '/g' for global in your regular expression. Otherwise only the first match gets replaced.

$(this).text(text.replace(/dog/g, 'doll')); 
like image 32
LcKjus Avatar answered Nov 17 '25 22:11

LcKjus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!