0

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);
1
  • Can we see the contents of the variable text? Is it of the form "my list of space-separated words"? Commented Jun 9, 2011 at 12:42

2 Answers 2

1

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);
});

See test case on jsFiddle

Sign up to request clarification or add additional context in comments.

6 Comments

I know the wrap, but as you can see in my code i need to wrap plain text, so certain words.
@user759235, that wasn't clear until you updated your question. Now my answer appears more or less out of context. I'll look for another solution. I recall doing the same a while back so should have something lying around :)
@user759235, updated answer! I hope this was more in line with what you were looking for ;)
This works, but not in the way that i use it, i use the code to highlight words in a piece of text, this is done true an input field, this means it live highlighting, the code above will mess up the piece of text if i enter more that 2 characters
If i change the text into html it will work, but the used code to wrap the words will be displayed to
|
0

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>';
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.