Dima
Dima

Reputation: 11

How to replace all the text in the text in a loop?

Sorry for my english =) I need to replace some of the elements on a page. Here is my code:

var text1 = $('body').html().replace(/text1/, 'text11');
var text2 = $('body').html().replace(/text2/, 'text22');
var text3 = $('body').html().replace(/text3/, 'text33');
array = [text1, text2, text3];
      for (var i = 0; i < array.length; i++) {
        $('body').html(array[i])
      };

But to replace only the first and third, if you remove the third element array, first and second is changed. Please tell me how to do it. Thank you!

Upvotes: 1

Views: 107

Answers (2)

Paul Fleming
Paul Fleming

Reputation: 24526

var items = [
    { find: /text1/, replace: 'text11' },
    { find: /text2/, replace: 'text22' },
    { find: /text3/, replace: 'text33' }
];
var text = $('body').html();

for (var i = 0; i < items.length; i++)
{
    var item = items[i];
    text = text.replace(item.find, item.replace);
}

$('body').html(text);

Upvotes: 2

Michal Klouda
Michal Klouda

Reputation: 14521

That's because the original body html remains unchanged when the variables are evaluated. You would need to chain the replaces or use the previous variables for another replaces:

var text1 = $('body').html().replace(/text1/, 'text11');
var text2 = text1.replace(/text2/, 'text22');
var text3 = text2.replace(/text3/, 'text33');

And then you don't need any iterations..

$('body').html(text3);

Upvotes: 2

Related Questions