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
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); Code (markup): Put inside a function and load it on body.onload or something, but use with care, narrow your search as much as possible.