简体   繁体   中英

How to highlight a part of string from given string in Javascript/Jquery

I have a string

   var inputStr = 'xzy';

   var match = 'x';

I have to highlight the str from the inputStr . I was trying something like this

var inputStr = "vikram";
var match = 'v';
var new_str = str.split('');

for(var i = 0;i<=new_str.length;i++)
{
    if(match == new_str[i])
    {
         var x_str += ''//code to bold that charachter and add in the array 
    }

}

Can any one please help me fix this

Thanks in advance

我建议乍一看:

var inputStr = inputStr.replace(new RegExp('(' + str + ')', 'g'), '<strong>$1</strong>');

For your question i found that you want to implement a search similar to that of the browser check out the Fiddle that i have created hope that helpes you.

[http://jsfiddle.net/raLnLyb4/][1]

var $search = 'vi';
var $names = $('.search_string p');
  var match = RegExp($search, 'gi');
  $names.filter(function(){ return match.test($(this).text()) })
    .html(function(){
      if (!$search) return $(this).text();
      return $(this).text().replace(match, '<span class="highlight">$&</span>');
});

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