JavaScript 字串 charCodeAt() 方法



JavaScript 字串 charCodeAt() 方法返回指定索引處介於 0 到 65535 之間的整數。該整數值被視為單個字元的 Unicode 值。索引從 0 開始,到 str.length-1 結束。

如果索引引數值不在 0str.length-1 的範圍內,則返回 'NaN'。

語法

以下是 JavaScript 字串 charCodeAt() 方法的語法:

charCodeAt(index)

引數

此方法接受一個可選引數,稱為“索引”,如下所述:

  • index − 字元的索引(位置)。

返回值

此方法返回指定索引處字元的 Unicode 值。

示例 1

當我們省略 index 引數時,此方法假設其索引引數的預設值為 0,並返回給定字串“Tutorials Point”中第一個字元“T”的 Unicode 值。

<html>
<head>
<title>JavaScript String charCodeAt() Method</title>
</head>
<body>
<script>
   const str = "Tutorials Point";
   document.write("String value = ", str);
   document.write("<br>The character code ", str.charCodeAt(), " is equal to ", str.charAt());
</script>
</body>
</html>

輸出

上述程式為字元“T”返回 Unicode 值 84。

String value = Tutorials Point
The character code 84 is equal to T

示例 2

如果我們將索引值作為 6 傳遞給此方法,它將返回指定索引處字元的 Unicode 值。

以下是 JavaScript 字串 charCodeAt() 方法的另一個示例。在這裡,我們使用此方法來檢索給定字串“Hello World”中指定索引 6 處字元的 Unicode 值。

<html>
<head>
<title>JavaScript String charCodeAt() Method</title>
</head>
<body>
<script>
   const str = "Hello World";
   document.write("String value = ", str);
   let index = 6;
   document.write("<br>Index value = ", index);
   document.write("<br>The character at ", index, "th position is: ", str.charAt(index));
   document.write("<br>The Unicode of a character '", str.charAt(index), "' is: ", str.charCodeAt(index));
</script>
</body>
</html>

輸出

執行上述程式後,它將返回字元“W”的 Unicode 值 87。

String value = Hello World
Index value = 6
The character at 6th position is: W
The Unicode of a character 'W' is: 87

示例 3

當索引引數不在 0str.length-1 之間時,此方法返回“NaN”。

我們可以透過執行下面的程式來驗證上述事實陳述,即如果索引引數超出 0 到 str.length-1 的範圍,charCodeAt() 方法將返回“NaN”。

<html>
<head>
<title>JavaScript String charCodeAt() Method</title>
</head>
<body>
<script>
   const str = "JavaScript";
   document.write("String value = ", str);
   let index = 15;
   document.write("<br>Index value = ", index);
   document.write("<br>The character at ", index, "th position is: ", str.charAt(index));
   document.write("<br>The Unicode of a character '", str.charAt(index), "' is: ", str.charCodeAt(50));
</script>
</body>
</html>

輸出

此方法將返回“NaN”,因為索引值超出範圍。

String value = JavaScript
Index value = 15
The character at 15th position is:
The Unicode of a character '' is: NaN
廣告