TextDecoder and TextEncoder in Javascript?

JavascriptWeb DevelopmentObject Oriented Programming

TextEncoder is used to convert a given string to utf-8 standard. It retunes an Uint8Array from the string.

TextDecoder is used to covert a stream of bytes into a stream of code points. It can decode UTF-8 , ISO-8859-2, KOI8-R, GBK etc.

Following is the code for TextDecoder and TextEncoder in JavaScript −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result,.sample {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
   .result {
      color: red;
   }
</style>
</head>
<body>
<h1>TextDecoder and TextEncoder in Javascript</h1>
<div class="sample"></div>
<button class="Btn">ENCODE STRING</button>
<div class="result"></div>
<h3>Click on the above button to encode the above string</h3>
<div class="sample"></div>
<button class="Btn">Decode STRING</button>
<div class="result"></div>
<h3>Click on the above button to decode the above string</h3>
<script>
   let BtnEle = document.querySelectorAll(".Btn");
   let sampleEle = document.querySelectorAll(".sample");
   let resEle = document.querySelectorAll(".result");
   let str = "Hello world";
   let str1 = new Uint8Array([119, 111, 114, 108, 100]);
   sampleEle[0].innerHTML = str;
   sampleEle[1].innerHTML = str1;
   BtnEle[0].addEventListener("click", () => {
      let textEncoder = new TextEncoder();
      resEle[0].innerHTML += "Encoded String = " + textEncoder.encode(str) + "<br>";
   });
   BtnEle[1].addEventListener("click", () => {
      let textDecoder = new TextDecoder();
      resEle[1].innerHTML += "Decoded String = " + textDecoder.decode(str1) + "<br>";
   });
</script>
</body>
</html>

Output

The above code will produce the following output −

On clicking the ‘ENCODE STRING’ button −

On clicking the ‘Decode STRING’ button −

raja
Updated on 17-Jul-2020 07:52:24

Advertisements