user1492226
user1492226

Reputation:

A simple javascript regex backreference

I have the following string that I am attempting to match:

REQS_HOME->31

The following Javascript code is attempting to match this:

pathRegExPattern = '(' + docTypeHome + ')' + '(->)' + '(\d+)';
parsedResult = pathCookieValue.match(pathRegExPattern);
cookieToDelete = docType + '_ScrollPos_' + $3;
alert(parsedResult);  // output - null

Assume the following:

docTypeHome = "REQS_HOME"
pathCookieValue = "REQS_HOME->31"

Firstly, I am not calling my match function properly. And secondly, how do I access the value where I am attempting to match the digit values using the backreference operator?

I need to extract the value 31.

Upvotes: 1

Views: 262

Answers (1)

Pointy
Pointy

Reputation: 413702

Your digit-matching part needs to double-up on the backslashes:

pathRegExPattern = '(' + docTypeHome + ')' + '(->)' + '(\\d+)';

When you build up a regular expression from string parts, the string syntax itself will "eat" a backslash. Thus, the regex you were winding up with was just d+, without the backslash.

The "31" (or whatever the number ends up being) will be in parsedResult[3]. Note that it'll be a string, so if you need it to be a number you'll want to convert it first, via the Number constructor, or parseInt(), or whatever.

Upvotes: 1

Related Questions