Search code examples
javascriptregexjszip

Replace URI prefix from Base64String using Regex


I'm working with JSZip download and there are some photo URI data which should be downloaded by FileSaver.

Photo URI looks like this:

photouri1 = 'data:image/jpeg;base64,/9a...';
photouri2 = 'data:image/png;base64,/9a...';

As you see, there are 2 types of photo URIs. Since zip.file api requires data to be base64String, I should replace URI prefix with empty string as follows:

...
var base64Str1 = photouri1.replace('data:image/jpeg;base64,', '');
zip.file('image1', base64Str1, { base64: true });
var base64Str1 = photouri1.replace('data:image/png;base64,', '');
zip.file('image2', base64Str2, { base64: true });
zip.generateAsync({ type: 'blob' }).then(...)

I want that replacing operation could be done at a time(batch operation) using a simple regex with for~loop.

Any suggestions? Thanks in advance.


Solution

  • You can try this

    ^.*base64,(?=\/)
    

    Explanation

    • ^ - Anchor to start of string.
    • .* - Will match anything except newline character zero or more time.(Greedy mode).
    • base64,- Will matchbase64,`.
    • (?=\/) - Positive lookahead will match /

    Demo