1

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.

2 Answers 2

4

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;
Sign up to request clarification or add additional context in comments.

Comments

0

Looks like, this works:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.