0

I have string which contain 5 to 6 word and i would like to replace some word with highlighter style.

$(document).ready(function() {
     var str = "Micromax Samsung S3 Microsoft Galaxy S";
     var arr = ["Micro", "s"];
     arr.forEach(function(item) {
          str = str.replace(new RegExp(item.replace(/\+/g, "\\+"), "g"), '<span class="red">'+ item +'</span>');
     })
     $('#dvHtml').html(str);
});

But i am getting every s in the entire string including but i don't want to replace .

Can any body help me to exclude or ignore following items from replace

  1. <span class="red">
  2. </span>

Output should be

Now this will replace Micro with <span class="red">Micro</span> and s with <span class="red">s</span>

Following are output enter image description here

2
  • 1
    What is it displaying right now? Commented Dec 30, 2013 at 7:50
  • 1
    Thanks for your comment, I have updated my question with output Commented Dec 30, 2013 at 7:58

3 Answers 3

3

You need change your regexp something like this

var str = "Micromax Samsung S3 Microsoft Galaxy S";
var arr = ["Micro", "s"];
var t = str.replace(new RegExp('\\b('+arr.join('|')+')',"gi"), '<span class="red">$1</span>');

$('#dvHtml').html(t);

in this

  • \b - find in begin word
  • arr.join('|') - return string like a|b - so find any of them
  • gi - flag for global and ignore case

you can try it on JSFiddle

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

9 Comments

You can't apply the same procedure to the string again... is that valid for the asker?
@EdgarVillegasAlvarado what you mean?
if you do str = t and then rerun the replace line, it breaks. Is it valid for the asker? Maybe it is
Or, if your initial str = 'Micromax <span class="red"> X </span> dd', it also breaks
@EdgarVillegasAlvarado i don't change source string, only save result to another string
|
2

Here you have another solution.

function escapeRegExp(str) {
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

function highlight(str, needle){      
      var parts = str.split(/<[/]?span.*?>/gi);
      for(var i=0; i<parts.length; i++){
          if(i%2 == 0){            
              parts[i] = parts[i].replace(new RegExp("("+escapeRegExp(needle)+")", 'gi'), '<span class="red">$1</span>');        
          }else{
              parts[i] = '<span class="red">'+ parts[i] +'</span>';                
          }
      }
      return parts.join('');    
}

$(document).ready(function() {
   var str = "Micromax Samsung S3 Microsoft Galaxy S";
   var arr = ["Micro", "S"];
   arr.forEach(function(item) {
        str = highlight(str, item);
   });
   console.log(str);
   $('#dvHtml').html(str);
});

The advantage of this one is that you can reapply the highlight method as many times as you want on the processed string.

JSFiddle: http://jsfiddle.net/edgarinvillegas/4ZK7W/2/

Also, you can have special characters in the string to search. For example, var arr = ["Micro", "Sam|"] does not highlight "Sam", but highlights "Sam|" if it existed in the str .

Cheers, from La Paz Bolivia

1 Comment

Excellent...really i appreciate your effort and it is really help me to escape char or string form sentence. my vote +
0

Don't reinvent the wheel. Here you have a highlight plugin that deals with that problem:

http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html

Hope it helps. Cheers, from La Paz, Bolivia

1 Comment

thanks for your answer, but i can not use this library due to some reason. can you help me to improve my answer

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.