TextDecoder and TextEncoder in Javascript?

TextEncoder and TextDecoder are modern JavaScript APIs that handle text encoding and decoding operations. TextEncoder converts strings to UTF-8 bytes, while TextDecoder converts byte arrays back to strings with support for multiple character encodings.

TextEncoder Overview

TextEncoder converts JavaScript strings into UTF-8 encoded Uint8Array. It only supports UTF-8 encoding and provides a simple encode() method.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>TextEncoder Example</title>
</head>
<body>
    <script>
        const encoder = new TextEncoder();
        const text = "Hello, World! ?";
        
        const encoded = encoder.encode(text);
        console.log("Original string:", text);
        console.log("Encoded bytes:", encoded);
        console.log("Byte length:", encoded.length);
        
        // Display results on page
        document.body.innerHTML = `
            <h3>TextEncoder Example</h3>
            <p><strong>Original:</strong> ${text}</p>
            <p><strong>Encoded:</strong> [${Array.from(encoded).join(', ')}]</p>
            <p><strong>Byte Length:</strong> ${encoded.length}</p>
        `;
    </script>
</body>
</html>

TextDecoder Overview

TextDecoder converts byte arrays back into strings. It supports multiple encodings including UTF-8, UTF-16, ISO-8859-1, and others.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>TextDecoder Example</title>
</head>
<body>
    <script>
        const decoder = new TextDecoder('utf-8');
        const bytes = new Uint8Array([72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33]);
        
        const decoded = decoder.decode(bytes);
        console.log("Byte array:", bytes);
        console.log("Decoded string:", decoded);
        
        // Display results
        document.body.innerHTML = `
            <h3>TextDecoder Example</h3>
            <p><strong>Bytes:</strong> [${Array.from(bytes).join(', ')}]</p>
            <p><strong>Decoded:</strong> ${decoded}</p>
        `;
    </script>
</body>
</html>

Complete Example: Encode and Decode

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>TextEncoder and TextDecoder</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .result { background: #f5f5f5; padding: 10px; margin: 10px 0; }
        button { padding: 10px 20px; margin: 5px; }
    </style>
</head>
<body>
    <h2>TextEncoder and TextDecoder Demo</h2>
    
    <div>
        <input type="text" id="textInput" value="Hello, JavaScript! ?" style="width: 300px;">
        <br><br>
        <button onclick="encodeText()">Encode Text</button>
        <button onclick="decodeBytes()">Decode Bytes</button>
    </div>
    
    <div id="results"></div>
    
    <script>
        let encodedData = null;
        
        function encodeText() {
            const text = document.getElementById('textInput').value;
            const encoder = new TextEncoder();
            encodedData = encoder.encode(text);
            
            document.getElementById('results').innerHTML = `
                <div class="result">
                    <h4>Encoding Results:</h4>
                    <p><strong>Original:</strong> ${text}</p>
                    <p><strong>Encoded bytes:</strong> [${Array.from(encodedData).join(', ')}]</p>
                    <p><strong>Length:</strong> ${encodedData.length} bytes</p>
                </div>
            `;
        }
        
        function decodeBytes() {
            if (!encodedData) {
                document.getElementById('results').innerHTML = 
                    '<div class="result">Please encode text first!</div>';
                return;
            }
            
            const decoder = new TextDecoder('utf-8');
            const decoded = decoder.decode(encodedData);
            
            document.getElementById('results').innerHTML += `
                <div class="result">
                    <h4>Decoding Results:</h4>
                    <p><strong>Bytes:</strong> [${Array.from(encodedData).join(', ')}]</p>
                    <p><strong>Decoded:</strong> ${decoded}</p>
                </div>
            `;
        }
    </script>
</body>
</html>

Supported Encodings

TextDecoder supports various character encodings:

Encoding Description Usage
utf-8 Default Unicode encoding Most common, supports all characters
utf-16 16-bit Unicode encoding Used in Windows systems
iso-8859-1 Latin-1 encoding Western European characters
windows-1252 Windows Latin encoding Windows legacy text files

Key Methods and Properties

// TextEncoder methods
const encoder = new TextEncoder();
encoder.encode(string)        // Returns Uint8Array
encoder.encoding             // Always "utf-8"

// TextDecoder methods
const decoder = new TextDecoder(encoding, options);
decoder.decode(buffer)       // Returns decoded string
decoder.encoding            // Returns encoding name

Browser Compatibility

TextEncoder and TextDecoder are supported in all modern browsers. For Node.js, they're available from version 11.0.0+ as global objects, and can be imported from the 'util' module in earlier versions.

Conclusion

TextEncoder and TextDecoder provide efficient ways to handle text encoding and decoding in JavaScript. TextEncoder converts strings to UTF-8 bytes, while TextDecoder supports multiple encodings for converting bytes back to strings.

Updated on: 2026-03-15T23:18:59+05:30

662 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements