Node.JS
Node.JS

Reputation: 1578

JavaScript regex look behind alternative

I am trying to match the following string into 2 groups using look behind but apparently, they are not supported in JavaScript.

Regex: ((?<=:).*(?=;))|((?<=,).*$)Online Demo

data:image/jpeg;base64,/abcd1234...

--> group1: image/jpeg
--> group2: /abcd1234...

Then I tried to use XRegExp library hoping it would support look behind but still no success.

var XRegExp = require("xregexp");
var base64 = "data:image/jpeg;base64,/abcd1234...";
base64 = XRegExp.matchRecursive(base64, '((?<=:).*(?=;))|((?<=,).*$)', 'g');

But I get the following error:

node_modules/xregexp/xregexp-all.js:3376
        new RegExp(generated.pattern, generated.flags),
        ^
SyntaxError: Invalid regular expression: /((?<=:).*(?=;))|((?<=,).*$)/: Invalid group at new RegExp (native)

Is there a way to run the regex using JavaScript's native regex parser probably by reversing the string?

Upvotes: 2

Views: 849

Answers (1)

revo
revo

Reputation: 48751

Be more specific:

(?=[^:;]*;)([^:;]+)|([^;,]+)$

Live demo

Or use more JS:

var re = /:([^:;]+);|,(.*)$/g;
var str = "data:image/jpeg;base64,/abcd1234...";
var matches;
while ((matches = re.exec(str)) !== null) {
  console.log(matches[1] ? matches[1] : matches[2])
}

Upvotes: 1

Related Questions