如何在 JavaScript 中将 Unicode 值转换为字符?

htmljavascriptprogramming scripts

在本教程中,我们将学习在 JavaScript 中将 Unicode 值转换为字符。Unicode 值是字符的标准值,用户可以对其进行编码以将其转换为字符。

例如,根据 ASCII(美国信息交换标准代码)表,'A' 是一个 Unicode 字符,其值为 65。同样,所有字母、数字和其他字符都有特定的 Unicode 值。我们将学习使用 JavaScript 从其值中识别 Unicode 字符。

使用 fromCharCode() 方法

在 JavaScript 中,字符串库包含 fromCharCode() 方法,该方法获取 Unicode 字符的十进制值并返回相关字符。此外,它以多个值作为参数,并返回组合所有字符后的字符串。

语法

我们可以按照以下语法使用 fromCharCode() 方法将 Unicode 值转换为字符。

String.fromCharCode( value );
String.fromCharCode( v1, v2, v3, v4, v5, … );

参数

  • − 它是 Unicode 字符的十进制值。

  • v1、v2、v3、… − 它们是不同或相同 Unicode 值的多个值。

示例 1

在下面的示例中,我们使用了 fromCharCode() 方法将不同的 Unicode 值转换为字符。我们将两个 Unicode 值 - 69 和 97 转换为字符。

<html> <head> </head> <body> <h2>Convert Unicode values to characters in JavaScript.</h2> <h4>Converting single Decimal Unicode value to character using the <i> fromCharCode() </i> method.</h4> <p id = "output"> </p> <script> let output = document.getElementById("output"); // converting different decimal values to characters let value = 69; let char = String.fromCharCode( value ); output.innerHTML += value + " to unicode character is : " + char + " <br/> "; char = String.fromCharCode( 97 ); output.innerHTML += 97 + " to unicode character is : " + char + " <br/> "; </script> </body> </html>

示例 2

在下面的程序中,我们使用 fromCharCode() 方法将多个 Unicode 值转换为字符。我们将两组 Unicode 值转换为字符串,第一组转换为"TutorialsPoint",第二组转换为"Hello"。

<html> <head> </head> <body> <h2>Convert Unicode values to characters in JavaScript. </h2> <h4>Converting multiple Decimal Unicode values to characters using the <i> fromCharCode() </i> method.</h4> <p id="output1"></p> <script> let output1 = document.getElementById("output1"); // converting multiple values to unicode characters in single pass. output1.innerHTML += " [84, 117, 116, 111, 114, 105, 97, 108, 115, 80, 111, 105, 110, 116] to Unicode character is : " + String.fromCharCode( 84, 117, 116, 111, 114, 105, 97, 108, 115, 80, 111, 105, 110, 116 ) + " <br/> "; output1.innerHTML += " [72, 69, 76, 76, 79] to Unicode character is : " + String.fromCharCode( 72, 69, 76, 76, 79 ) + " <br/> "; </script> </body> </html>

在上面的输出中,用户可以看到,当我们将多个 Unicode 字符值传递给 fromCharCode() 方法时,它会输出相关 Unicode 字符的字符串。

用户已经学习并理解了 fromCharCode() 方法如何将 Unicode 值转换为 Unicode 字符。用户可以使用 fromCharCode() 方法,无论是单个值还是用逗号分隔的多个值。


相关文章