开发者

Auto link specific words and phrases

开发者 https://www.devze.com 2022-12-11 21:58 出处:网络
C开发者_Go百科an I use jQuery, another library or standard javascript to list a series of words and phrases that I would like to be auto linked?

C开发者_Go百科an 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!


You can use the javascript replace() function.

$("#myid").html().replace('word one', '<a href="http://www.something.com">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">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">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.

0

精彩评论

暂无评论...
验证码 换一张
取 消