如何從 Unicode 數字獲取字元 - JavaScript?
在本文中,我們將學習如何在 JavaScript 中從 Unicode 數字獲取字元。在開始講解之前,讓我們快速瞭解一下 JavaScript 中的 Unicode 數字。
JavaScript 中的 Unicode 轉義序列可用於表示用 Unicode 編寫的識別符號和字串文字。四位十六進位制值 X 表示基本語法,即 uXXXX。
讓我們深入文章,瞭解更多關於“如何在 JavaScript 中從 Unicode 數字獲取字元”的資訊。要從 Unicode 數字檢索字元,請在 JavaScript 中使用 String.fromCharCode()
JavaScript 中的 String.fromCharCode() 方法
JavaScript 字串方法 charCodeAt() 可用於查詢字串中特定位置的字元的 Unicode 值。由於 charCodeAt() 方法是 String 物件的方法,因此必須透過 String 類的特定例項呼叫它。
語法
以下是 String.fromCharCode() 的語法:
string.charCodeAt([position]);
為了更好地理解,讓我們看看下面的例子
示例
讓我們看看下面的例子,瞭解如何在 JavaScript 中使用 CharCode()
<!DOCTYPE html> <html> <body> <script> var tutorial_string = 'ABCDEFGHI'; document.write(tutorial_string.charCodeAt(0)+"<br>"); document.write(tutorial_string.charCodeAt(1)+"<br>"); document.write(tutorial_string.charCodeAt(2)+"<br>"); document.write(tutorial_string.charCodeAt(3)+"<br>"); </script> </body> </html>
當指令碼執行時,它將生成一個輸出,其中包含為我們在上述指令碼中使用的字串獲得的 Unicode 值。當指令碼中觸發事件時,就會發生這種情況。
示例
考慮另一個例子,我們獲取兩個字元的 Unicode 值
<!DOCTYPE html> <html> <body> <p>Getting the Unicode Value:</p> <p id="tutorial"></p> <script> let text = "WELCOME"; let code = text.charCodeAt(2); document.getElementById("tutorial").innerHTML = code; </script> </body> </html>
執行上述指令碼後,網頁瀏覽器將觸發事件,並顯示文字以及我們在指令碼中使用的文字的第二個字元的 Unicode 值。
示例
讓我們看看另一個例子,我們沒有傳遞任何引數
<!DOCTYPE html> <html> <body> <p>Getting the Unicode Value:</p> <p id="tutorial"></p> <script> var tutorial_string = 'TutorialsPoint'; document.getElementById("tutorial").innerHTML = (tutorial_string.charCodeAt()); </script> </body> </html>
當指令碼執行時,它將生成一個輸出,其中包含在網頁上列印的文字和 Unicode 值。因為我們沒有指定任何引數來返回值,所以指令碼在執行時會檢查引數以返回值。如果預設情況下找不到引數,它將使用引數“0”並顯示 Unicode 值。
示例
執行以下程式碼,其中我們提到的引數超出範圍
<!DOCTYPE html> <html> <body> <p>Getting the Unicode Value:</p> <p id="tutorial"></p> <script> var tutorial_string = 'The Best E-Way'; document.getElementById("tutorial").innerHTML = (tutorial_string.charCodeAt(22)); </script> </body> </html>
在這種情況下,當用戶執行指令碼時,將觸發事件,檢查字串和引數值,並返回值。我們提到的引數值超過了字串計數,超出了範圍,因此它將返回 Unicode 值為 NaN。