I am trying to match a part of the string and it should be NOT case sensitive. I have the following code but I never get the replaced string.
var name = 'Mohammad Azam'
var result = name.replace('/' + searchText + '/gi', "<b>" + searchText + "</b>");
The searchText variable will be "moha" or "mo" or "moh".
How can I get the matching thing in bold tags.
Regular expression (regexp): It is a particular syntax /pattern/modifiers; modifier sets the type. For example /GeeksforGeeks/i where “i” sets to case insensitive. Note: Here g and i used for global and case-insensitive search respectively.
Regular expression, or simply RegEx JavaScript allows you to write specific search patterns. You can also make the search case-sensitive or insensitive, search for a single JavaScript RegEx match or multiple, look for characters at the beginning or the end of a word.
Comparing strings in a case insensitive manner means to compare them without taking care of the uppercase and lowercase letters. To perform this operation the most preferred method is to use either toUpperCase() or toLowerCase() function.
/pattern/ has meaning when it's put in as a literal, not if you construct string like that. (I am not 100% sure on that.)
Try
var name = 'Mohammad Azam';
var searchText = 'moha';
var result = name.replace(new RegExp('(' + searchText + ')', 'gi'), "<b>$1</b>");
//result is <b>Moha</b>mmad Azam
EDIT:
Added the demo page for the above code.
Demo →
Code
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With