简体   繁体   中英

Regexp match everything after a word

I am trying to extract the base64 string from a data-url. The string looks like this, so I am trying to extract everything after the word base64

test = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQAB'

So I want to extract the following from the above string

,/9j/4AAQSkZJRgABAQAAAQAB

Here is my regex

const base64rgx = new RegExp('(?<=base64)(?s)(.*$)');
console.log(test.match(base64rgx))

But this fails with the error:

 VM3616:1 Uncaught SyntaxError: Invalid regular expression: /(?<=base64)(?s)(.*$)/: Invalid group

It appears that lookbehinds are not being supported. But the good news is that you don't need a lookaround here, the following pattern should work:

 test = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQAB' var regex = /.*?base64(.*?)/g; var match = regex.exec(test); console.log(match[1]); 

I'm not sure precisely how much of the string after base64 you want to capture. If, for example, you don't want the comma, or the 9j portion, then we can easily modify the pattern to handle that.

 var test = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQAB'; var regex = /(?<=base64).+/; var r = test.match(regex); console.log(r); 

Here's the regex: https://regex101.com/r/uzyu0a/1

You may not need regular expression: just find base64 string with indexOf and use substr

 var test = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQAB'; var data = test.substr(test.indexOf('base64')+6); // 6 is length of "base64" string console.log(data); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM