2

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?

5
  • Why are you trying to pick apart a data URL? Where is it coming from, and what do you plan to do with it? Commented Jul 7, 2017 at 5:28
  • @torazaburo My highest priority is to extract mime type from it Commented Jul 7, 2017 at 5:30
  • I would prefer to GET the URL with responseType set to Blob, then consult the type property of the resulting blob. Commented Jul 7, 2017 at 5:39
  • Why do you need a lookbehind? Can't you just do :(.*);|,(.*$)? Commented Jul 7, 2017 at 5:56
  • 1
    Look-behinds were added in the 2018 specification. They work in Chrome, but Firefox has a bug due to lack of implementation. Commented Dec 8, 2019 at 0:25

1 Answer 1

1

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])
}

Sign up to request clarification or add additional context in comments.

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.