mirror of
https://github.com/CorentinTh/it-tools.git
synced 2025-04-22 07:46:15 -04:00
refactor(base64): mutualized base64 functions into global utilities
This commit is contained in:
parent
ca7cb44389
commit
447bdf2148
8 changed files with 138 additions and 12 deletions
33
src/utils/base64.ts
Normal file
33
src/utils/base64.ts
Normal file
|
@ -0,0 +1,33 @@
|
|||
export { textToBase64, base64ToText, isValidBase64, removePotentialDataAndMimePrefix };
|
||||
|
||||
function textToBase64(str: string) {
|
||||
return window.btoa(str);
|
||||
}
|
||||
|
||||
function base64ToText(str: string) {
|
||||
if (!isValidBase64(str)) {
|
||||
throw new Error('Incorrect base64 string');
|
||||
}
|
||||
|
||||
const cleanStr = removePotentialDataAndMimePrefix(str);
|
||||
|
||||
try {
|
||||
return window.atob(cleanStr);
|
||||
} catch (_) {
|
||||
throw new Error('Incorrect base64 string');
|
||||
}
|
||||
}
|
||||
|
||||
function removePotentialDataAndMimePrefix(str: string) {
|
||||
return str.replace(/^data:.*?;base64,/, '');
|
||||
}
|
||||
|
||||
function isValidBase64(str: string) {
|
||||
const cleanStr = removePotentialDataAndMimePrefix(str);
|
||||
|
||||
try {
|
||||
return window.btoa(window.atob(cleanStr)) === cleanStr;
|
||||
} catch (err) {
|
||||
return false;
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue