View Full Version : Question about Hyperlink Coding

03-19-2009, 01:49 AM
Hello all,

I'm relatively new to programming with Javascript and am working on some basic coding. I'm looking to see if there is a simpler line of code for a inserting a hyperlink at each occurrence of a specific word. I searched throughout the forums and couldn't find anything, but then again I probably don't know which particular code to use. Any advice would be much appreciated.


03-19-2009, 03:07 AM

var needle = "textToReplace";
var target = "http://www.google.com";
var replacement = "replacementText";
var paragraph = document.getElementById("targetElement").innerHTML;
document.getElementById("targetElement").innerHTML = paragraph.replace(needle,"<a href='" + target + "'>" + replacement + "</a>");

Hopefully that'll do it.

Old Pedant
03-19-2009, 03:20 AM
Not quite right, pds.

replace in JS takes a regular expression as the first argument. If you give it just a string, then it defaults to NOT-ignore case and NOT-global. The first might be okay, but the second means only the first occurrence will be replaced.

So you'd need to use:

var needle = "textToReplace";
var target = "http://www.google.com";
var replacement = "replacementText";
var paragraph = document.getElementById("targetElement");
var re = new RegExp(needle,"g"); // and maybe "ig"
paragraph.innerHTML =
paragraph.innerHTML.replace(re,"<a href='" + target + "'>" + replacement + "</a>");

Old Pedant
03-19-2009, 03:25 AM
Also, if you want to leave the word in place and only surround it with the link, and if you want to ignore case for finding the word but leave the case alone in the replacement, you'll need to do something like this:

var word = "someWord"
var replacement="<a href='http://www.google.com'>$1</a>"

var re = new RegExp("(" + word + ")","g"); // and maybe "ig"

var paragraph = document.getElementById("targetElement");
paragraph.innerHTML = paragraph.innerHTML.replace(re, replacement );


Old Pedant
03-19-2009, 03:42 AM
That code also has its problems. If your word is (for example) "to", then you will end up highlighting the "to" in other words such as "sTOp" and "Toot" and so on.

So here is, I think the "ultimate" solution:

function highlight(word, indiv)
var replacement="$1<a href='http://www.google.com'><b>$2</b></a>$3"

var re = new RegExp("(^|\\W)(" + word + ")(\\W|$)","ig");

var paragraph = document.getElementById(indiv);
paragraph.innerHTML = paragraph.innerHTML.replace(re, replacement );

<div id="foo">Now is the time for all good men to come to!</div>
<div id="bar">To toot your horn you stop and STOP and Stop!</div>

highlight("stop","bar"); // try it without this line, first

03-19-2009, 05:00 AM
awesome. Cool script OP. Thanks

03-19-2009, 05:04 AM
Unfortunately I'm having trouble thanking people, otherwise I would. Good catch, I'll have to read up on Regular Expressions.