pedroyanky pedroyanky - 3 months ago 8
Javascript Question

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?

Answer

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>

Comments