<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
<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
- possible duplicate of Replace all occurances in javascript – GillesC Commented Aug 7, 2015 at 7:44
5 Answers
Reset to default 9Your 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>
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'));
You can use .text
with callback, and use regex with /g
modifier
$('#id1').text(function(index, text) {
return text.replace(/dog/g, 'doll');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="id1">
apple
ball
dogsss
dogsss
dogsss
</div>
Instead of using replace()
, use split()
and join()
, which will replace all occurrences instead of just the first one:
$('#id1').each(function() {
var text = $(this).text();
$(this).text(text.split("dog").join("doll"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="id1">
apple
ball
dogsss
dogsss
dogsss
</div>
That's it:
$('#id1').text(function(index, oldText) {
return oldText.replace(/dog/g, 'doll');
})
// or not use a function
// $('#id1').text($('#id1').text().replace(/dog/g, 'doll'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="id1">
apple ball dogsss dogsssdogsss dogsssdogsssdogsss
</div>