1

I have this string:

global_filter[default_fields[0]]

I want to convert it to this string:

global_filter[dashboard_fields[0]]

I would like to use the replace function to detect the matched substring 'default_fields' and then replace it with 'dashboard_fields'.

First I try this:

var str = "global_filter[default_fields[0]]";
var regex = /\w+\[(.+)\[\d+\]\]/;
str.replace(regex, function(match, index){
  console.log(match); console.log(index);
});
=> global_filter[default_fields[0]]
=> default_fields

For some strange reason, the matched substring comes as the index argument, not the match argument. The index argument is supposed to be a position where the match is found. So obviously, I am doing something wrong. So I try to use positive lookahead instead:

str.replace(/(?=\w+\[).+(?=\[\d+\]\])/, function(match, index){
  console.log(match); console.log(index);
})
=> global_filter[default_fields
=> 0

That clearly does not work either. How am I supposed to make match equal the substring I want?

2
  • Um var str = global_filter[default_fields[0]]; I do not see the string. Are you missing the quotes? Commented Oct 7, 2015 at 21:44
  • 1
    Given what you just said, can you literally replace('default_fields', 'dashboard_fields')? Commented Oct 7, 2015 at 21:45

2 Answers 2

1

You don't need to replace callback function, just use captured groups as:

var str = "global_filter[default_fields[0]]";
str = str.replace(/(\w+\[).+?(\[\d+\]\])/g, '$1dashboard_fields$2');
//=> global_filter[dashboard_fields[0]]

Reason why you're seeing a captured group when you print index is because index is always supposed to be last argument of callback function after all the matched groups. Do note that you have (.+) as a captured group.

So if you use:

str.replace(/\w+\[(.+)\[\d+\]\]/, function(m0, m1, index){
  console.log(m0); console.log(index);
});

Then it will correctly print:

global_filter[default_fields[0]]
0
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for answer. Can you also explain why the replace function is passing a string for the index argument, when the index is supposed to be the position where the string was found.
0

You don't have to use a regular expression, you can just use a string.

var str = 'global_filter[default_fields[0]]';

console.log(str.replace('default','dashboard'));

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.