15

I have this function :

function boldString(str, find){
   return str.replace(find, '<b>'+find+'</b>');
}

It works, except that it is case sensitive.

I could to-lower-case the str and find text before running the replace, But I want the function to return the original capitalization in the str field

So if I pass in 'Apple' for the str, and 'ap' for the find, I want the function to return 'Apple'.

Wyatt
  • 445
  • 3
  • 12

1 Answers1

27

With a case-insensitive regular expression:

function boldString(str, find) {
  var reg = new RegExp('('+find+')', 'gi');
  return str.replace(reg, '<b>$1</b>');
}
console.log(boldString('Apple', 'ap'))
tklg
  • 2,572
  • 2
  • 19
  • 24