Okay, I've update this question with improved code from the answers and comments below and more similar to the real project. But still it's not working in IE8. fiddle here
<ul id="definitions">
<li id="defid63">keyword1<input type="hidden" value="63" /></li>
<li id="defid61">keyword2<input type="hidden" value="61" /></li>
<li id="defid62">Keyword3<input type="hidden" value="62" /></li>
</ul>
<div id="html">Lorem ipsum keyword1 dolor keyword2 sit keyword3 amet, consectetur adipisicing elit, sed do eiusmod tempor</div>
I've a list (ul > li
) of keywords and there is a string with some text. I would like to wrap each occurrence of a keyword with an <a>
-tag. I've code which works fine in firefox and chrome, but IE(8) doesn't match the regex somehow.
jQuery(function($) {
// created by Gracenotes
// http://goo.gl/MTkcY
RegExp.quote = function(str) {
return str.replace(/([.?*+^$[\]\\(){}-])/g, "\\$1");
};
var $node = $('#html'),
// the dom element
html = $node.html(); // the text we'll manipulate
$('#definitions li').each(function() {
var defid = $(this).find('input').val(),
deftext = $(this).html().split("<input")[0],
//the keyword
//pattern = eval('/\\b('+RegExp.quote(deftext)+')\\b/gi');
pattern = new RegExp('\\b(' + RegExp.quote(deftext) + ')\\b', 'gi');
html = html.replace(pattern, '<a href="#id=' + defid + '">$1</a>');
});
// replace the dom content with our updated text
$node.html(html);
});