简体   繁体   中英

Replace with regExp in javascript

I have a problem with replace like this:

I have an array test :

test: Object
    boolean: "true"
    integer: "0"
    values|+|0: "option_1"
    values|+|1: "option_2"

and then i do parse like this:

for(var data in test){
   for(var input in test[data]){
   var input_aux = input.split('|+|');
   if(input != ''){
      $('table#'+table_id+' tbody td.'+input_aux[0]+' small').each(function(){ 
       var text_highlighted = $(this).text().replace(new RegExp('(' + test[table][input] + ')', 'gi'), '<b>$1<\/b>');
      $(this).html(text_highlighted);
    }}}

what i'm trying to accomplish is to match the data from the array like option_1 that is in that table exactly option_1 and change the html of it to <b>option_1</b> .

And it's working fine my problem is like when i have the same key but different value like in the example above, it will highlight only option_2 and can't understand why, any idea?

The issue is the fact you are doing replacements even if there is no match. So you are reading the text() of all the elements and replacing it with that text. So you wipe out all of the existing html.

So check to see if there is a match before you do the replacement.

var re = new RegExp('(' + test[table][input] + ')', 'gi');
var txt = $(this).text();
if (txt.match(re)) {
    var text_highlighted = txt.replace(re, '<b>$1<\/b>');
    $(this).html(text_highlighted);
}

other option would be to use contains selector .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM