0

I'm using RegExp in some javascript code which I'm using to replace a string that looks like this:

[1]

With one that looks like this:

[2]

This all works OK, however I would only like to do this, if the preceding character is not a:

]

So

something[1] should become something[2]

But

something[1][somethingelse][1] should become something[2][somethingelse][1]

My current code looks like this:

var first = 1;
var count = 2;
var pattern = escapeRegExp("[" + first + "]");
var regex = new RegExp(pattern, 'g');

$(this).html().replace(regex, '['+count+']'));

Any advice appreciated.

Thanks

3 Answers 3

2

You can have a negated character class before [1] part, that will match any character other than ]. And capture it in a group:

var pattern = escapeRegExp("([^\\]])[" + first + "]");
var regex = new RegExp(pattern, 'g');

$(this).html().replace(regex, '$1['+count+']'));
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I ended up using this approach, just had to escape the square brackets in the second part too.
2

What you need are Lookarounds. Try this regex:

/(?<!\[)\[1\]/[2]/

Edit: Since I was just informed that JS doesn't support this, you could try negated character-classes.

/[^\[]\[1\]/[2]/

1 Comment

Is that so? Thanks for mentioning that, I'm going to edit my answer then.
1

As a replacement for the missing lookbehind, capture the previous char in a group and put it back when replacing:

str = "foo[1] bar[2] baz[3][somethingelse][1]"
re = /([^\]])\[(\d+)\]/g
str.replace(re, function($0, $1, $2) { 
   return $1 + '[' + (1 + Number($2)) + ']' 
})

> "foo[2] bar[3] baz[4][somethingelse][1]"

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.