5

I have a regex pattern like this:

([0-9]*)xyz

I wish to do substitution like this:

$10xyz

The problem is that the $1 is a capture group and the 0 is just a number I want to put into the substitution. But regex thinks I'm asking for capture group $10 instead of $1 and then a zero after it.

How do I reference a capture group and immediately follow it with a number?

Using JavaScript in this case.

UPDATE As pointed out below, my code did work fine. The regex tester I was using was accidentally set to PCRE instead of JavaScript.

Jake Wilson
  • 78,902
  • 83
  • 230
  • 344

2 Answers2

5

Your code indeed works just fine. In JavaScript regular expression replacement syntax $10 references capturing group 10. However, if group 10 has not been set, group 1 gets inserted then the literal 0 afterwards.

var r = '123xyz'.replace(/([0-9]*)xyz/, '$10xyz');
console.log(r); //=> "1230xyz"
hwnd
  • 65,661
  • 4
  • 77
  • 114
1

Your code does work unless I'm missing something:

var str = "3xyz";
var str1 = str.replace(/([0-9]*)xyz/, "$10xyz");
alert(str1); // alerts 30xyz
eatonphil
  • 10,877
  • 21
  • 66
  • 118