JavaScript String fromCharCode() Method



The JavaScript String fromCharCode() method is a static method that converts a Unicode value (or a sequence of Unicode values) to the character(s) and returns a new string.

As discussed, that the fromCharCode() method is a static method of the String object, so it should always be used as String.fromCharCode(), rather than invoking it on a variable like x.fromCharCode(), where 'x' is a variable.

Syntax

Following is the syntax of JavaScript String fromCharCode() method −

String.fromCharCode(num1, num2, /*..., */ numN)

Parameters

This method accepts one or more parameters of the same type, which are Unicode values. The same is described below −

  • num1, num2,.....numN − A one or more Unicode values that needs to be converted.

Return value

This method returns a string created from specified unicode values.

Example 1

In the following program, we are using the JavaScript String fromCharCode() method to retrieve a character value of the specified Unicode value 100.

<html>
<head>
<title>JavaScript String fromCharCode() Method</title>
</head>
<body>
<script>
   let unicode = 100;
   document.write("Unicode value: ", unicode);
   document.write("<br>The unicode value ", unicode ," represents to character: ", String.fromCharCode(unicode));
</script>    
</body>
</html>

Output

The above program returns 'd'.

Unicode value: 100
The unicode value 100 represents to character: d

Example 2

As the String fromCharCode() method accepts one or more parameters of the same type, you can pass multiple Unicode values to it, and it will return a new string from the specified sequence of the Unicode values.

<html>
<head>
<title>JavaScript String fromCharCode() Method</title>
</head>
<body>
<script>
   let u1 = 190;
   let u2 = 43;
   let u3 = 190;
   document.write("Unicode values are: ", u1, ", ", u2, ", ", u3);
   document.write("<br>New string: ", String.fromCharCode(u1, u2, u3));
</script>    
</body>
</html>

Output

After executing the above program, it will return a new string "".

Unicode values are: 190, 43, 190
New string: ¾+¾

Example 3

As discussed, this is a static method, so always use it, String.fromCharCode(). But let's see what happens if we invoke this method on a variable like var.fromCharCode() rather than invoking it on a String object.

<html>
<head>
<title>JavaScript String fromCharCode() Method</title>
</head>
<body>
<script>
   let unicode_value = 65;//unicode of char 'A'
   document.write("Unicode value: ", unicode_value);
   try {
      document.write("<br>Unicode ", unicode_value, " represents to character: ", unicode_value.fromCharCode(unicode_value));
   } catch (error) {
      document.write("<br>", error);
   }
</script>    
</body>
</html>

Output

The above program returns a 'TypeError' exception.

Unicode value: 65
TypeError: unicode_value.fromCharCode is not a function
Advertisements