Reputation: 2207
I use the jQuery html Attributes to wrap some words in a large piece of text, this works fine but if the text has some html tags in it, it will remove all tags. Is there a way to prevent this with the html Attributes, preventing that i strips the other tags?
piece of the code
var pattern = new RegExp('('+$.unique(text.replace(/\./g, '\\.').split(" ")).join("|")+")","gi");
jQuery('searchin').each(function(i){
var orgText = jQuery(this).text();
orgText = orgText.replace(pattern, function($1){
return '<b class="highlight">' + $1 + '</b>';
});
jQuery(this).html(orgText);
Upvotes: 0
Views: 150
Reputation: 97571
You can write Marcus Ekwall's answer in a much more concise way:
jQuery('p').html(function(i, oldValue) {
return oldValue.replace(pattern, function($1) {
return '<strong>' + $1 + '</strong>';
});
});
Upvotes: 0
Reputation: 28974
That should work if you replace .text()
with .html()
, like this:
jQuery('p').each(function(i){
// replaced .text() with .html()
var orgText = jQuery(this).html();
orgText = orgText.replace(pattern, function($1){
return '<strong>' + $1 + '</strong>';
});
jQuery(this).html(orgText);
});
Upvotes: 1