0

Is it possible for javascript to to create multiple new variables using RegEx back references? Something like:

var temp = fileName.replace(new RegExp( "(^.)(.*)(_.*)(-.*)", "i" ),"\$1\$2\$3\$4");
var first = $1;
var forth = $4;

In perl I would do something like this:

$uprate =~ /(^.)(.*)(_.*)(-.*)/$1 $2 $3 $4/;

$first = $1;
$forth = $4;
cubicalmonkey
  • 105
  • 2
  • 12
  • Those are not back refs, they're just memory captures. Just remove the backslash should make it work. – Ja͢ck Mar 09 '13 at 02:55
  • Possible duplicate [How do you access the matched groups in a javascript regex?](http://stackoverflow.com/questions/432493/how-do-you-access-the-matched-groups-in-a-javascript-regex). – juan.facorro Mar 09 '13 at 03:00

1 Answers1

3

Try using the Javascript String's match method. It will return an object containing all matched groups.

var matches = fileName.match(/(^.)(.*)(_.*)(-.*)/i);
var first = matches[1];
var fourth = matches[4];

The match method will return null if the string doesn't match the regex, so be sure to test for that unless you're certain it will succeed.

cspotcode
  • 1,832
  • 1
  • 13
  • 17