1

I'm writing a javascript function which takes a regex and some elements against which it matches the regex against the name attribute.

Let's say i'm passed this regex

/cmw_step_attributes\]\[\d*\]/

and a string that is structured like this

"foo[bar][]chicken[123][cmw_step_attributes][456][name]"

where all the numbers could vary, or be missing. I want to match the regex against the string in order to swap out the 456 for another number (which will vary), eg 789. So, i want to end up with

"foo[bar][]chicken[123][cmw_step_attributes][789][name]"

The regex will match the string, but i can't swap out the whole regex for 789 as that will wipe out the "[cmw_step_attributes][" bit. There must be a clean and simple way to do this but i can't get my head round it. Any ideas?

thanks, max

Max Williams
  • 30,785
  • 29
  • 115
  • 186

4 Answers4

2

Capture the first part and put it back into the string.

.replace(/(cmw_step_attributes\]\[)\d*/, '$1789');
// note I removed the closing ] from the end - quantifiers are greedy so all numbers are selected
// alternatively:
.replace(/cmw_step_attributes\]\[\d*\]/, 'cmw_step_attributes][789]')
Niet the Dark Absol
  • 301,028
  • 70
  • 427
  • 540
1

Either literally rewrite part that must remain the same in replacement string, or place it inside capturing brackets and reference it in replace.

Oleg V. Volkov
  • 19,811
  • 3
  • 40
  • 60
1

See answer on: Regular Expression to match outer brackets.

Regular expressions are the wrong tool for the job because you are dealing with nested structures, i.e. recursion.

Community
  • 1
  • 1
Madara's Ghost
  • 158,961
  • 49
  • 244
  • 292
1

Have you tried:

var str = 'foo[bar][]chicken[123][cmw_step_attributes][456][name]';
str.replace(/cmw_step_attributes\]\[\d*?\]/gi, 'cmw_step_attributes][XXX]');
Petah
  • 42,792
  • 26
  • 149
  • 203
  • That would work but how do i do it dynamically, ie if i can get passed through any regex to match against the string, and want to switch out the \d part? – Max Williams May 02 '12 at 15:51
  • @MaxWilliams so like any thing in replace of `cmw_step_attributes`? – Petah May 02 '12 at 17:11