9

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
  • What do you want to replace searchText with? Literal string 'searchText' or something else? Commented Jul 27, 2009 at 1:29

2 Answers 2

23

/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

Sign up to request clarification or add additional context in comments.

4 Comments

You do not have to construct RegExp's with a parenthesis
He wants to capture the match and surround it with <b> and </b> tags. You can't do capturing without parenthesis.
Yes you can when the search string is identical to the replacement sans surrounding tags.
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!
3

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"

1 Comment

heh, I confused myself with what you were looking for - let me know if either of those workout.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.