Enrichman
Enrichman

Reputation: 11337

Javascript regex to replace last digit occurence between square brackets?

I've been looking for this for hours, right now I've ended in a very ugly way (but working). I would like to find a reusable nice way to do this.

I've a string like this:

wanna[0].some[0].javascript

I would like to replace the last digit occurence between square brackets:

wanna[0].some[1].javascript

I've ended this (ugly) way:

myString.replace(/\d].javascript$/, "1].javascript")

which should be the best regex to match that?

myString.replace(/\d/, 1) // this should be for the first digit
myString.replace(/\d/g, 1) // this for every digit

I've read about negative look-ahead but I still didn't get if JS supports this.

Upvotes: 2

Views: 1407

Answers (2)

guypursey
guypursey

Reputation: 3184

Not sure why you need lookahead. The answer you gave (though ugly) should work. As Crockford says of negative lookaheads in JavaScript: The Good Parts: 'This is not a good part.'

If the line you provided isn't working I imagine it's because you haven't escaped the square bracket. It should be:

myString.replace(/\d\].javascript$/, "1].javascript");

You could also do some capturing to make it easier on the eye.

I agree with the comment to your question that it seems like an odd problem to solve. Why are you changing the number in a string? This looks like something that would be better served with a number variable in the square brackets that you can then increment.

Upvotes: 0

Joseph Silber
Joseph Silber

Reputation: 219938

Just use a negative lookahead to ascertain that there are no more brackets after the one you're matching:

var text = 'wanna[0].some[0].javascript';

text = text.replace(/\[\d](?!.*\[)/, '[1]');

Here's the fiddle: http://jsfiddle.net/bRkEP/

Upvotes: 4

Related Questions