Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
42
rated 0 times [  43] [ 1]  / answers: 1 / hits: 46606  / 8 Years ago, thu, july 28, 2016, 12:00:00

I am currently doing the following to decode base64 images in Javascript:



    var strImage = ;
strImage = strToReplace.replace(data:image/jpeg;base64,, );
strImage = strToReplace.replace(data:image/png;base64,, );
strImage = strToReplace.replace(data:image/gif;base64,, );
strImage = strToReplace.replace(data:image/bmp;base64,, );


As you can see above we are accepting the four most standard image types (jpeg, png, gif, bmp);



However, some of these images are very large and scanning through each one 4-5 times with replace seems a dreadful waste and terribly inefficient.



Is there a way I could reliably strip the data:image part of a base64 image string in a single pass?



Perhaps by detecting the first comma in the string?



Thanks in advance.


More From » string

 Answers
76

You can use a regular expression:



var strImage = strToReplace.replace(/^data:image/[a-z]+;base64,/, );






  • ^ means At the start of the string

  • data:image means data:image

  • / means /

  • [a-z]+ means One or more characters between a and z

  • ;base64, means ;base64,


[#61225] Tuesday, July 26, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nadineannabellet

Total Points: 464
Total Questions: 94
Total Answers: 97

Location: Maldives
Member since Tue, Dec 21, 2021
2 Years ago
;