Javascript replace a specific number of times - help

Discussion in 'JavaScript' started by trepxe-oes, Dec 4, 2007.

  1. #1
    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
     
    trepxe-oes, Dec 4, 2007 IP
  2. hrcerqueira

    hrcerqueira Peon

    Messages:
    125
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #2
    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.
     
    hrcerqueira, Dec 5, 2007 IP