CoderZone.org

Category: >> JavaScript >> Auto-Link words Bookmark and Share

<< lastnext >>

Snippet Name: Auto-Link words

Description: Automatically turns every instance of a word into a link.

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

Comment: (none)

Author: CoderZone
Language: JAVASCRIPT
Highlight Mode: JAVASCRIPT
Last Modified: February 27th, 2009

/* 
  linkWord(obj)
  written by Christian Heilmann (http://wait-till-i.com)
  automatically turns words defined in the object obj into 
  hyperlink. 
  The object obj sent as a paramater needs to contain all the words
  properties and the associated URLs as values.
  Demo object: 
  {
    'wait-till-i.com':'http://wait-till-i.com',
    'icant.co.uk':'http://icant.co.uk'
  }
*/
 
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
 
Settings:
 
{
  'example':'http://www.example.com',
  'another':'http://icant.co.uk'
}
 
There haven't been any comments added for this snippet yet. You may add one if you like.  Add a comment 
© coderzone.org | users online: 6