Andrii Radkevych
Andrii Radkevych

Reputation: 3442

remove data:image/png;base64, from generated base64 string

export const convertFileToBase64 = file => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()

    reader.readAsDataURL(file)

    reader.onload = () => {
      if (reader.result) {
        resolve(reader.result)
      } else {
        reject(Error('Failed converting to base64'))
      }
    }
  })
}

What i wan't is to understand is it possible to generate base 64 without addition data:image/png;base64, at the beginning of the string, maybe someone say user string replace method , and remove it , but I also wait on png file, pdf file , etc. Is it possible to improve my method and remove it ?

Upvotes: 1

Views: 3690

Answers (2)

Ouroborus
Ouroborus

Reputation: 16886

Just split the string on the comma and get the part after.

const getDataPart = (dataUrl) => dataUrl.split(',', 1)[1];

console.log(getDataPart('data:image/png;base64,somebase64stuff'));

Coincidentally, this works on any data url encoding as a comma is a required part of the format and is the only piece that separates the data from the rest.

Upvotes: 1

J.F.
J.F.

Reputation: 15207

If I've understood correctly you can achieve your goal using regex and replace() like this.

const str1 = "data:image/png;base64,moredatablablabla"
const str2 = "data:application/pdf;base64,datadatadatablabla"

const regex = /data:.*base64,/
console.log(str1.replace(regex,""))
console.log(str2.replace(regex,""))

Upvotes: 7

Related Questions