Paul
Paul

Reputation: 3954

Regex Invalid Group

Can anyone see why this is giving an Invalid regular expression: Invalid group error?

text.replace(/(?<!br|p|\/p|b|\/b)>/g, "&gt;");

This one is OK:

text.replace(/<(?!br|p|\/p|b|\/b)/g, "&lt;");

So, I'm not sure where I'm going wrong with the first one (&gt;).

Here's a fiddle with an example.

Upvotes: 3

Views: 3230

Answers (1)

Andrew Clark
Andrew Clark

Reputation: 208405

JavaScript does not support lookbehinds. Here is one way you can get the same behavior:

text = text.replace(/(br|p|\/p|b|\/b)?>/g, function($0, $1){
    return $1 ? $0 : "&gt;";
});

This approach comes from the following blog entry: Mimicking Lookbehind in JavaScript

Here is an updated fiddle.

Upvotes: 3

Related Questions