Sandeep Bansal
Sandeep Bansal

Reputation: 6394

Using * in regex as a value to lookup

I'm trying to replace all occurrences of a string ***deal*** When I use the following code I receive a Quantifier {x,y} following nothing error.

var regex = new RegExp('***deal***', 'g');
Content=Content.replace(regex, DEAL);

Can anyone fill me in how I'm supposed to get past the error?

As a note I'm using Server Side Javascript with a .NET backend.

Thanks

Upvotes: 0

Views: 72

Answers (2)

Ivan Solntsev
Ivan Solntsev

Reputation: 2118

Special characters in Regular Expressions escaped by backslash \

var regex = new RegExp('\\*\\*\\*deal\\*\\*\\*', 'g');

in string values, you also need to escape \ resulting '\\'

Upvotes: 1

Tim Pietzcker
Tim Pietzcker

Reputation: 336128

* is a metacharacter (meaning "zero or more of the preceding token", and there is nothing preceding the *s in your regex, hence the error message) that needs to be escaped:

var regex = /\*\*\*deal\*\*\*/g;

I've used a regex literal because that allows you to cut down on the number of backslashes; the equivalent using a regex constructor would be

var regex = new RegExp('\\*\\*\\*deal\\*\\*\\*', 'g');

Upvotes: 3

Related Questions