I see at least two problems.
The \
character has a special meaning in JavaScript strings. It is used to escape special characters in the string. For example: \n
is a new line
, and \r
is a carriage return
. You can also escape quotes and apostrophes to include them in your string: "This isn't a normally \"quoted\" string... It has actual \" characters inside the string as well as delimiting it."
The second problem is that, in order to use a backreference ($1
, $2
, etc.) you must provide a capturing group
in your pattern (the regex needs to know what to backreference). Try changing your pattern to:
'\\[' + section + '\\]\\[(\\d+)\\]'
Note the double-backslashes. This escapes the backslash character itself, allowing it to be a literal \
in a string. Also note the use of (
and )
(the capturing group). This tells the regex what to capture for $1
.
After the regex is instantiated, with section === 'abc'
:
new RegExp('\\[' + section + '\\]\\[(\\d+)\\]', 'g');
Your pattern is now:
/\[abc\]\[(\d+)\]/g
And your .replace
will return \d+++
(where \d+
is the captured digits from the input string).
Demo: http://jsfiddle.net/U46yx/