admin管理员组

文章数量:1188831

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.

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.

Share Improve this question edited Jul 27, 2009 at 1:34 azamsharp asked Jul 27, 2009 at 1:24 azamsharpazamsharp 20.1k38 gold badges147 silver badges230 bronze badges 1
  • What do you want to replace searchText with? Literal string 'searchText' or something else? – SolutionYogi Commented Jul 27, 2009 at 1:29
Add a comment  | 

2 Answers 2

Reset to default 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

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"

本文标签: JavaScript Regex Ignore CaseStack Overflow