Automatically turning every instance of a word into a link

This was a request by Fizzy on twitter, he wanted to have a small function that automatically turns every instance of a word into a link.

Comment on the blog

Whilst functionality like this is best done on the server side, there might be a need for a JavaScript solution, so here goes:

  written by Christian Heilmann (
  automatically turns words defined in the object obj into 
  The object obj sent as a paramater needs to contain all the words
  properties and the associated URLs as values.
  Demo object: 
function linkWord(obj){
  for(i in obj){
    var x = document.body.innerHTML;
    var linkStart = '<a href="'+obj[i]+'">';	
    var linkEnd = '</a>';	
    var reg = new RegExp ('\\b' + i + '\\b','g');
    x = x.replace(reg, linkStart + i + linkEnd);
    document.body.innerHTML = x;

Demo output follows



This is an example

More examples and another example