Kyrotomia
Kyrotomia

Reputation: 158

Javascript regex grouping

I am trying to create a regular expression that would easily replace an input name such as "holes[0][shots][0][unit]" to "holes[0][shots]1[unit]". I'm basically cloning a HTML input and would like to make sure its position is incremented.

I got my regex built and working correctly using this (awesome) tool : http://gskinner.com/RegExr/

Here is my current regex :

(.*\[shots\]\[)([0-9]+)(\].*\])

and I am using a replace such as :

$12$3

this transforms "holes[0][shots][0][unit]" into "holes[0][shots][2][unit]". This is exactly want I want. However, when I try this in javascript (http://jsfiddle.net/PH2Rh/) :

var str = "holes[0][shots][0][units]";
var reg =new RegExp("(.*\[shots\]\[)([0-9]+)(\].*\])", "g");

console.log(str.replace(​reg,'$1'));​​​​​​​​​​​​​​​​​​​​​​​​

I get the following output : holes[0

I don't understand how my first group is supposed to represent "holes[0", since I included the whole [shots][ part in it.

I appreciate any inputs on this. THank you.

Upvotes: 1

Views: 383

Answers (2)

rpeshkov
rpeshkov

Reputation: 5047

Looks like, this works:

var str = "holes[0][shots][0][units]";
var reg = /(.*\[shots\]\[)([0-9]+)(\].*\])/;
console.log(str.replace(​reg,'$1'));​​​​​​​​​​​​​​​​​​​​​​​​

Upvotes: 0

Rob W
Rob W

Reputation: 348992

In strings, a single \ is not interpreted as a Regex-escaping character. To escape the bracket within string literals, you have to use two backslashes, \\:

var reg = new RegExp("(.*\\[shots\\]\\[)([0-9]+)(\\].*\\])", "g");

A preferable solution is to use RegEx literals:

var reg = /(.*\[shots\]\[)([0-9]+)(\].*\])/g;

Upvotes: 4

Related Questions