btoa() एक बाइनरी स्ट्रिंग लेता है जिसकी हर इकाई एक बाइट में आती है। यह अपने आप UTF-8 नहीं बनाता। हिंदी और कई Unicode अक्षर InvalidCharacterError दे सकते हैं; पहले टेक्स्ट को UTF-8 बाइट में बदलें।
UTF-8 एन्कोड और डिकोड करें
TextEncoder टेक्स्ट से बाइट बनाता है। नीचे का कोड btoa से पहले छोटे समूह इस्तेमाल करता है ताकि फ़ंक्शन आर्गुमेंट की सीमा न आए। डिकोड करते समय atob के परिणाम से Uint8Array बनाएँ और TextDecoder इस्तेमाल करें। fatal विकल्प अमान्य UTF-8 बाइट पर त्रुटि देता है।
पूरा रूपांतरण जाँचें
안녕하세요 😀 का Base64 7JWI64WV7ZWY7IS47JqUIPCfmIA= है। डिकोडिंग में वही टेक्स्ट और स्पेस लौटने चाहिए। उदाहरण लिंक में निश्चित सार्वजनिक उदाहरण का नाम है, आपका टेक्स्ट URL में नहीं जाता। Decodex ब्राउज़र में अधिकतम 5 MB UTF-8 टेक्स्ट बदलता है।
त्रुटि का चरण पहचानें
atob की त्रुटि अक्सर अक्षर, पैडिंग या प्रीफिक्स से संबंधित होती है। TextDecoder की त्रुटि बाइनरी डेटा या दूसरी कैरेक्टर एन्कोडिंग दर्शा सकती है। Node.js में Buffer.from(text, "utf8").toString("base64") इस्तेमाल करें; ढीला डिकोडर इनपुट सत्यापन का विकल्प नहीं है।
यह उदाहरण बदलें
// Browser JavaScript: text → UTF-8 bytes → Base64.
function utf8ToBase64(text) {
const bytes = new TextEncoder().encode(text);
let binary = '';
for (let i = 0; i < bytes.length; i += 8192) {
binary += String.fromCharCode(...bytes.subarray(i, i + 8192));
}
return btoa(binary);
}
// Accept standard Base64 or Base64URL, with complete or omitted padding.
function base64ToUtf8(value) {
let normalized = value.replace(/\s/g, '').replace(/-/g, '+').replace(/_/g, '/');
if (!/^[A-Za-z0-9+/]*={0,2}$/.test(normalized) ||
normalized.length % 4 === 1 ||
(normalized.includes('=') && normalized.length % 4 !== 0)) {
throw new Error('Invalid Base64 characters, length or padding');
}
normalized += '='.repeat((4 - normalized.length % 4) % 4);
const binary = atob(normalized);
const bytes = Uint8Array.from(binary, character => character.charCodeAt(0));
return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
}
const text = '안녕하세요 😀';
const encoded = utf8ToBase64(text);
console.log(encoded); // 7JWI64WV7ZWY7IS47JqUIPCfmIA=
console.log(base64ToUtf8(encoded)); // 안녕하세요 😀
अक्सर पूछे जाने वाले प्रश्न
क्या atob सीधे हिंदी टेक्स्ट देता है?
नहीं। यह बाइनरी स्ट्रिंग देता है। मानों को Uint8Array में बदलें और TextDecoder("utf-8") से पढ़ें। पुराने unescape() वाले तरीके से बचें।
