Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Regex Ignore Case

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.

like image 870
azamsharp Avatar asked Jul 27 '09 01:07

azamsharp


People also ask

Which regular expression in JS ignores the case sensitivity?

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.

Is JavaScript regex case sensitive?

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.

How do you make a case insensitive in JavaScript?

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.


1 Answers

/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

like image 94
SolutionYogi Avatar answered Sep 22 '22 13:09

SolutionYogi