Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 541
Paul Avatar asked May 13 '26 03:05

Paul


1 Answers

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.

like image 186
Andrew Clark Avatar answered May 14 '26 15:05

Andrew Clark