views:

158

answers:

2

Hi,

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.

+1  A: 

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"
meder
heh, I confused myself with what you were looking for - let me know if either of those workout.
meder
You were right the first time :) It's a replace not a match
Ian Elliott
+1  A: 
SolutionYogi
You **do not** have to construct RegExp's with a parenthesis
Ian Elliott
He wants to capture the match and surround it with <b> and </b> tags.You can't do capturing without parenthesis.
SolutionYogi
Yes you can when the search string is identical to the replacement sans surrounding tags.
Ian Elliott
So, actually I should be sending the Regex object into the replace and not a string when performing these case operations. Thanks a lot man!
azamsharp
?? Could downvoter clarify why he downvoted?
SolutionYogi