Web API | TextDecoder decode() Method
The decode() method in TextDecoder API is used to takes a stream of bytes as input and emits a stream of code points. The TextEncoder decode() method takes an ArrayBuffer containing the encoded data and options object and returns the original string (i.e. decoded string).
Syntax:
decoder.decode(buffer, options)
Parameters:
- buffer: It is an ArrayBuffer, Dataview or TypedArray instance that contains the encoded data.
- options: It is an optional parameter that holds an object containing some properties.
- stream: It is a boolean value. It is set to true if data are processing in chunks and false if data are not chunked (by default its value set to false)
Return Value: It decodes the encoded input in buffer and returns the decoded string.
Example 1:
<!DOCTYPE html>
<html lang="en">
<head>
<title>
TextEncoder Web API
encodeInto() method
</title>
</head>
<body>
<p id='javascript'>I Love javascript</p>
<script type="text/javascript">
// Original string
const original = document.querySelector(
'#javascript').textContent
// Instance of TextEncoder
const encoder = new TextEncoder()
// Instance of TextDecoder
const decoder = new TextDecoder()
// encode() is just an another method
// defined in TextEncoder class
// It specifies the encoded result
// of strings
const encodedResult = encoder.encode(original)
// Decoding
const decodedResult = decoder.decode(encodedResult)
console.log(`
Original String: ${original},
Encoded Value: ${encodedResult},
Decoded Value: ${decodedResult}
`)
</script>
</body>
</html>
Output:

Example 2:
<!DOCTYPE html>
<html lang="en">
<head>
<title>GFG TextEncoder encodeInto() method</title>
</head>
<body>
<p id='javascript' hidden>I Love javascript</p>
<button id='btn'>Click me to see results</button>
<div id='result'></div>
<script type="text/javascript">
// Original string
const original = document.querySelector(
'#javascript').textContent
const btn = document.querySelector('#btn')
const result = document.querySelector('#result')
// Instance of TextEncoder
const encoder = new TextEncoder()
// Instance of TextDecoder
const decoder = new TextDecoder()
// encode() is just an another method
// defined in TextEncoder class
// It specifies the encoded result of strings
const encodedResult = encoder.encode(original)
// Decoding
const decodedResult = decoder.decode(encodedResult)
// Button listing for click event, when
// click occurs shows original string and
// Encoded and Decode values
btn.addEventListener('click', () => {
result.innerHTML = `
Original: ${original}
Encoded Value: ${encodedResult}
Decoded Value: ${decodedResult}`
})
</script>
</body>
</html>
Output:
Before Clicking the Button:

After Clicking the Button:

Supported Browsers:
- Google Chrome 38 and above
- Edge 79 and above
- Firefox 19 and above
- Internet Explorer not supported
- Opera 25 and above
- Safari 10.1 and above