purplehey
purplehey

Reputation: 127

What is the difference between RegExp("str","i") and '/'+"str"+'/i'

I tried to do a case insensitive regular expression search by creating a string like so:

var regEx = '/'+myStr+'/i';

but when I use it in a search, it always returns -1.

If I use:

var regEx = RegExp(myStr,'i');

it works like a champ.

I'd just like to understand why?

Upvotes: 0

Views: 184

Answers (1)

Alexander O'Mara
Alexander O'Mara

Reputation: 60577

You first example will create a string, not a regular expression object.

var myStr = 'test';
var regEx = '/'+myStr+'/i';
console.log(typeof regEx);//string

Using RegExp will create a regular expression object.

var myStr = 'test';
var regEx = RegExp(myStr,'i');
console.log(typeof regEx);//object

Thus when you try to use the search method, you are searching with a string on slashes on both sides, thus getting -1.

var s = 'just a test string';
console.log(s.search('/test/'));//-1
console.log(s.search(/test/));//7

Of course, the string search method can work with a string, in which case it will search for that specific substring, which in your case does not exist, so it returns the -1 index. In your example slashes were being added to the string, rather than producing the intended regular expression.


In JavaScript, there are two ways of creating a regular expression object (short of using code evaluation), a regular expression literal, and one created by the RegExp constructor.

A regular expression literal has to be defined at compile time, and cannot be constructed from string concatenation.

/test/i

To dynamically create a regular expression at runtime, you have to use the RegExp constructor.

RegExp('test', 'i');

Upvotes: 4

Related Questions