Search and Replace

The javascript below is looking for the word ‘margaret thatcher’ in the body and surrounding it with a link. It’s lower-case but the script is ignoring the case so that won’t matter. But, the problem is that because Margaret Thatcher is a proper noun, it will be capitalized in the body text yet replaced with lower-case text. How can I modify this script to look for the word while ignoring the case but use the same text it found as the replacement instead of using the text object?

<script type="text/javascript">

searchObj=new Object();

//The following lines define the text that you want to 
//replace with hyperlinks.  to add a new one just add a new
//property to the object and then add the text and link 
//with a comma between them
searchObj.link1="margaret thatcher,http://www.bbc.co.uk";

function linkWord(obj){

  for(i in obj){
    var x = document.getElementById('text').innerHTML;
    var linkStart = '<a href="'+obj[i].substring(obj[i].indexOf(",")+1)+'">';
    var linkEnd = '</a>';
    var reg = new RegExp ('\\\\b' + obj[i].substring(0, obj[i].indexOf(",")) + '\\\\b','gim');
    x = x.replace(reg, linkStart + obj[i].substring(0, obj[i].indexOf(",")) + linkEnd);
    document.getElementById('text').innerHTML = x;
    //alert(linkStart);
  }
}
</script>

</head> 
<body onLoad="linkWord(searchObj);"> 

...

One easy solution is to simply write “Margaret Thatcher” with the capital letters in your searchObj.link1. That’s what it’s getting replaced with anyway.

The alternative is to capture the searched string and put it in the replacement:

function linkWord(obj){

  for(i in obj){
    var x = document.getElementById('text').innerHTML;
    var linkStart = '<a href="'+obj[i].substring(obj[i].indexOf(",")+1)+'">';
    var linkEnd = '</a>';
    var reg = new RegExp ('\\\\b(' + obj[i].substring(0, obj[i].indexOf(",")) + ')\\\\b','gim');
    x = x.replace(reg, linkStart + '$1' + linkEnd);
    document.getElementById('text').innerHTML = x;
    //alert(linkStart);
  }
}

The index of words I’m working on have all been lower-cased long ago so your REGEXP fix is fantastic! Thank you!