Shopping news - Debt Consolidation - Debt Consolidation - Wordpress Themes - Debt Consolidation

PDA

View Full Version : Javascript replace a specific number of times - help


trepxe-oes
Dec 4th 2007, 9:23 pm
Hello friends,

I want to use replace function in javascript but the client wants that a particular word should be replaced a specified number of times. For example...

In a particular page, I want to replace first 5 occurances of the word 'Telecom' to 'Telecommunications'. No matter how many times this word is used in the specified page.

Please help

hrcerqueira
Dec 5th 2007, 7:43 am
Try this:


var bodytext = document.body.innerHTML;
var oldtext = 'PHP';
var newtext = 'COOL';
var ntimes = 5;
var max;

for (var i = 0, tmp = 0, max = 0; i <= ntimes && tmp >= 0; i++) {
var tmp = bodytext.indexOf(oldtext, max);
if (tmp >= 0)
max = tmp + oldtext.length;
}

var firstpiece = bodytext.substring(0, max);
var secondpiece = bodytext.substring(max, bodytext.length);

document.body.innerHTML = firstpiece.replace(new RegExp(oldtext, 'g'), newtext) + secondpiece.substring(max, bodytext.length);



Put inside a function and load it on body.onload or something, but use with care, narrow your search as much as possible.