I want to replace specific words (laptop, asus, acer) with links (test.com/l12, test.com/13, test.com/14) using jQuery. I found this function
<script type="text/javascript">
(function($) {
var thePage = $("body");
thePage.text(thePage.html().replace(/laptop/ig, '<a href="http://test.com/laptop">laptop</a>'));
})(jQuery)
</script>
but the problem is that it replaces laptop word in existing urls开发者_StackOverflow (creating urls like test.com/test.com/laptop-review if the url was test.com/laptop-review) and all the laptop html (html ids, classes, urls etc) on the page is destroyed.
Thank you
You could do:
$('body *').each(function(){
var txt = $(this).text();
txt = txt.replace('laptop', '<a href="http://test.com/laptop">laptop</a>');
$(this).html(txt);
});
fiddle http://jsfiddle.net/LXw6P/
EDIT of course you could make this a function and reuse it:
var updateTxt = function(stringToReplace){
var replaceText = '<a href="http://test.com/'+stringToReplace'+">'+stringToReplace+'</a>';
$('body *').each(function(){
var txt = $(this).text();
txt = txt.replace(stringToReplace, replaceText);
$(this).html(txt);
});
}
use it:
updateTxt('laptop');
You could try using the jQuery text replace plug-in - http://net.tutsplus.com/tutorials/javascript-ajax/spotlight-jquery-replacetext/
The plug-in should ignore HTML mark-up and only change 'text' values.
Further details are given in this question - How do I do a case insensitive search for a word and convert it to a hyperlink using jquery?
精彩评论