0

Trying to match x occurance of a string using javascript regex :

var regex = new RegExp("(?:\[([0-9]+\]{1}$)",'g')
string.replace(regex, '[3]');

String source :

sometext[2][markers][2][title]

Expected results :

sometext[2][markers][3][title]

What is wrong with the regex?

Edit : Changed the regex to : regex = new RegExp("(?:[([0-9]+]{" + Filter + "})",'g');

The results, javascript is changing all the [x]: sometext[3][markers][3][title]

3

1 Answer 1

1

The RegEx: "\[\d+\]"

\[    First, an open square bracket (escaped)
\d    This means a digit (this is the same as [0-9])
+     The plus means there can be as many digits as you wish
\]    Ending it up with an escaped close bracket.

Note: We can use /\[\d+\]/g as a replacement for new RegEx(regex) and another benefit is that we don't have to double escape the characters (escaping the character in RegEx, and also escaping the backslash so JS will treat it as a normal backslash).


Change replaceThe to replace the nth occurrence.

var string = 'sometext[2][markers][2][title]';
var replaceThe = 2; // Replace the -second- occurrence
var i = 0;
string = string.replace(/\[\d+\]/g,
             function(m) { return (replaceThe == (++i) ? '[3]' : m); })

The last line uses an overload of the string.replace function which accepts a function. This function will be called for each match and the m parameter will be set to the match itself. The function is expected to return a replacement for the match. This way we can wait until the nth occurrence until we actually replace the match, otherwise we return the match we received, and that way it won't be replaced.

Sign up to request clarification or add additional context in comments.

4 Comments

Good, but be aware that you're creating the regex using a regex literal. If you write it as a string literal like the OP did, you should escape the backslashes as per the comment above.
Actually, this is exactly why I chose to create it literally
So I assumed, but I originally thought the "\[\d+\]" represented a JavaScript string literal, and you were making the same mistake as the OP. Now I see you were using it to illustrate the error. you should add some text to explain that. An answer isn't really an answer if doesn't explain (in words, not in source code) what the problem was.
I agree, I was in a rush when I gave the answer. Added some explaining.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.