1

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

3
  • what is length.new_str?? Commented Sep 9, 2014 at 11:01
  • 1
    You're looking for string.replace. Commented Sep 9, 2014 at 11:02
  • @Neel sorry it was a typo . I fixed it Commented Sep 9, 2014 at 11:04

2 Answers 2

1

I'd suggest, at first glance:

var inputStr = inputStr.replace(new RegExp('(' + str + ')', 'g'), '<strong>$1</strong>');
Sign up to request clarification or add additional context in comments.

2 Comments

What is str has a special character like ( or $ or .
@anubhava in my case it will not have any special character because I was trying to modify the . Old Auto complete plugin of Jquery . It is already filtering the special characters . this is more than enough :).
1

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

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.