Reputation: 20066
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.
Upvotes: 9
Views: 25143
Reputation: 32233
/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.
Upvotes: 23
Reputation: 186562
I think you're looking for new RegExp, which creates a dynamic regular expression - what you're trying to do now is match a string ( not a regexp object ) :
var name = 'Mohammad Azam', searchText='moha';
var result = name.replace(new RegExp(searchText, 'gi'), "" + searchText + ""); result
EDIT: Actually, this is probably what you were looking for, nevermind ^
var name = 'Mohammad Azam', searchText='moha';
name.match( new RegExp( searchText , 'gi' ) )[0]
name // "Moha"
Upvotes: 3