Javascript replace exactly words and only once.

Discussion in 'JavaScript' started by alexio, Jan 20, 2009.

  1. #1
    Hello,
    I am have a javascript code I do replace some words of content pages.

    The code is:

    
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
       "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <style type="text/css">
    .toolTip {
    cursor: help;
    font-weight: bold;
    }
    </style>
    </head>
    <body>
    <div>Bucuresti, I think Sibiu is a Hot Oradea.<br>
    Hello and welcome in Oradea to this great sporting event.<br>
    <span>Sibiu</span><br>Bucuresti
    </div>
    <script type="text/javascript">
    
    ;(function(){
     var addTips = {
      Oradea : 'Capital of Bihor County in Crisana, Romania',
      Sibiu : 'Capital of Sibiu County, Located some 282 km NW of Bucharest',
      Bucuresti : 'Capital City, Industrial, and Commercial Center of Romania'
     },
     tipWords = [], allTableData = document.getElementsByTagName('td'),
     allTableHeaders = document.getElementsByTagName('div'),
     collections = [allTableData, allTableHeaders],
     carve = function(tnm, cn){
      var text = cn.nodeValue.replace(tipWords, '?!$').split('?!$');
      for(var tip, n = [], i = 0; i < text.length; ++i){
       n.push(document.createTextNode(text[i]));
       if(tnm[i]){
        tip = document.createElement('span');
        tip.className = 'toolTip';
        tip.title = addTips[tnm[i]];
        tip.appendChild(document.createTextNode(tnm[i]));
        n.push(tip);
       }
     }
     for (var i = n.length - 1; i > -1; --i)
      i == n.length - 1? cn.parentNode.replaceChild(n[i], cn) : n[i+1].parentNode.insertBefore(n[i], n[i+1]);
     };
     for (var p in addTips)
      if (addTips.hasOwnProperty(p))
       tipWords.push(p);
     tipWords = new RegExp('(' + tipWords.join(')|(') + ')', 'g');
     for (var k = collections.length - 1; k > -1; --k)
      for (var cn, tnm, i = collections[k].length - 1; i > -1; --i){
       cn = collections[k][i].childNodes;
       for (var j = cn.length - 1; j > -1; --j)
        if(cn[j].nodeType == 3 && (tnm = cn[j].nodeValue.match(tipWords)))
         carve(tnm, cn[j]);
     }
    })();
    
    </script>
    </body>
    </html>
    
    Code (markup):
    I can help someone to change the script so that you do the following:

    1) Words in text Bucuresti and Oradea repeated the script I do replace all the words, I would like to replace a word only once.

    2) I'd like to be replace only if the word is exactly and not replace the word if for example found Bucurestilor i like to not replace with Bucuresti.

    I would be deeply grateful if you can help me, thank you.
     
    alexio, Jan 20, 2009 IP