views:

178

answers:

1

Hi All!

Can I use jQuery, another library or standard javascript to list a series of words and phrases that I would like to be auto linked?

For example:

Word / phrase 1: link to www.something.com
Word / phrase 2: link to www.somethingelse.com
Word / phrase 3: link to www.anotherlink.org

And so on.

Thanks in advance for your help!

A: 

You can use the javascript replace() function.

$("#myid").html().replace('word one', '<a href="http://www.something.com"&gt;word one</a>');

See http://www.tizag.com/javascriptT/javascript-string-replace.php for more information.

EDIT

The above only replaces the first instance of "word one". To replace everything, you'll need to use regular expressions.

$("#myid").html().replace(/word one/g, '<a href="http://www.something.com"&gt;word one</a>');

Replace "word one" with the text you want to replace.

EDIT 2

To answer your question in the comment, you need to capture the output. For example:

 $("#myid").html($("#myid").html().replace(/word one/g, '<a href="http://www.something.com"&gt;word one</a>'));

replace() isn't part of jQuery, and as such doesn't actually modify the DOM. replace() returns the modified string, so you need to do the leg work to write the modified string back to the page.

Kyle Trauberman
Sorry if this is a really freekin stupid question BUT, I have added a test as follows: <script type="text/javascript">$("#showcaseInfo").html().replace(/Jackson/g, '<a href="http://www.blah.com.au">Jacksonb</a>');</script> Doesn't seem to work.
Jackson
See my edit above.
Kyle Trauberman