如何在 JavaScript 中將 Unicode 值轉換為字元?
在本教程中,我們將學習如何在 JavaScript 中將 Unicode 值轉換為字元。Unicode 值是字元的標準值,使用者可以對其進行編碼以將其轉換為字元。
例如,‘A’ 是一個 Unicode 字元,根據ASCII(美國資訊交換標準程式碼)表,其值為65。同樣,所有字母、數字和其他字元都有特定的 Unicode 值。我們將學習使用 JavaScript 透過其值識別 Unicode 字元。
使用 fromCharCode() 方法
在 JavaScript 中,字串庫包含fromCharCode() 方法,該方法獲取 Unicode 字元的十進位制值並返回相關字元。此外,它還將多個值作為引數,並在組合所有字元後返回字串。
語法
我們可以按照以下語法使用 fromCharCode() 方法將 Unicode 值轉換為字元。
String.fromCharCode( value ); String.fromCharCode( v1, v2, v3, v4, v5, … );
引數
value − 它是 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 值轉換為 char 字串,第一組為“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() 方法,無論是單個值還是用逗號分隔的多個值。
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP