Reputation: 323
i tried to replace a text string using the jquery regular expression, instead am texts are multiplying by 4 instead of just replacing the match.
code:
var $div = $('#container div');
$div.text($div.text().replace(/division/ig, 'div'));
<div id="container">
<div>this is the first division element</div>
<div>this is the second division element</div>
<div>this is the third division element</div>
<div>this is the fourth division element</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
From what i saw in a material, this code should work fine. But somehow it is not producing the expected results.Could someone please point me in the right direction?
Upvotes: 2
Views: 54
Reputation: 393
You can loop over each div
element using $(...).each
like:
var $div = $('#container div');
$div.each(function() {
var text = $(this).text().replace(/division/ig, 'div');
$(this).text(text);
});
Upvotes: 1
Reputation: 562
var $div = $('#container div');
$div.each(function(index, value){
$(this).text($(this).text().replace(/division/ig, 'div'));
});
Upvotes: -1
Reputation: 82
As mentioned, you need to loop over each element that has been selected. You can do this in jquery:
$('#container div').each(function(idx) {
$( this ).text(function(i, text) {
return text.replace(/division/ig, 'div');
});
});
Upvotes: -1
Reputation: 12452
You have to use a loop, or a callback function, because you're having multiple elements.
$('#container div').text(function(i, text) {
return text.replace(/division/ig, 'div');
});
Example:
$('#container div').text(function(i, text) {
return text.replace(/division/ig, 'div');
});
<div id="container">
<div>this is the first division element</div>
<div>this is the second division element</div>
<div>this is the third division element</div>
<div>this is the fourth division element</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Upvotes: 4