Dan
Dan

Reputation: 6553

Javascript regex with exception

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

Upvotes: 0

Views: 496

Answers (3)

georg
georg

Reputation: 214949

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]"

Upvotes: 1

Vince
Vince

Reputation: 1527

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]/

Upvotes: 2

Rohit Jain
Rohit Jain

Reputation: 213213

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+']'));

Upvotes: 2

Related Questions