pedroyanky
pedroyanky

Reputation: 323

why is the jquery regular expression producing wierd result

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

Answers (4)

saaaaaaaaasha
saaaaaaaaasha

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

atul
atul

Reputation: 562

var $div = $('#container div');
$div.each(function(index, value){
  $(this).text($(this).text().replace(/division/ig, 'div'));
});

Upvotes: -1

paddybasi
paddybasi

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

eisbehr
eisbehr

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');
});

jQuery.text() documentation.

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

Related Questions