Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript | case-insensitive string replace [duplicate]

Tags:

javascript

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'.

like image 309
Wyatt Avatar asked Feb 09 '17 01:02

Wyatt


1 Answers

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'))
like image 138
Villa7_ Avatar answered Oct 24 '22 03:10

Villa7_