简体   繁体   English

用javascript中的regExp替换

[英]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> . 我要完成的工作是匹配该表中与option_1之类的数组中的数据完全相同的option_1 ,并将其html更改为<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? 而且工作正常,我的问题就像当我具有相同的键但值不同(如上例中所示)时,它将仅突出显示option_2 ,并且不明白为什么,有什么想法吗?

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. 因此,您正在阅读所有元素的text()并将其替换为该文本。 So you wipe out all of the existing html. 因此,您将清除所有现有的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 . 另一种选择是使用包含选择器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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