JavaScript 字串 charAt() 方法



JavaScript 字串 charAt() 方法返回一個新字串,其中包含原始字串中給定索引處的單個字元。索引是字串中字元的位置,從第一個字元的 0 開始,到最後一個字元的 n-1 結束,其中 n 是字串的長度。

注意 - 如果給定的索引值超出 0 到 str.length-1 的範圍,則此方法返回空字串。它還將空格視為有效字元,並將其包含在輸出中。

語法

以下是 JavaScript 字串 charAt() 方法的語法 -

charAt(index)

引數

此方法採用一個名為“index”的可選引數,如下所述 -

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

返回值

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

示例 1

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

<html>
<head>
<title>JavaScript String charAt() Method</title>
</head>
<body>
<script>
   const str = "Tutorials Point";
   document.write("str = ", str);
   document.write("<br>str.charAt() returns = ", str.charAt());
</script>
</body>
</html>

輸出

上述程式返回預設索引(0)處的字元'T'。

str = Tutorials Point
str.charAt() returns = T

示例 2

如果我們將索引值作為 6 傳遞給此方法,它將返回一個新字串,其中包含指定索引處的單個字元。

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

<html>
<head>
<title>JavaScript String charAt() Method</title>
</head>
<body>
<script>
   const str = "Hello World";
   document.write("str = ", str);
   let index = 6;
   document.write("<br>index = ", index);
   document.write("<br>The character at index ", index ," is = ", str.charAt(index));
</script>
</body>
</html>

輸出

執行上述程式後,它將返回指定索引 6 處的字元 'W'。

str = Hello World
index = 6
The character at index 6 is = W

示例 3

當 index 引數不在 0str.length-1 之間時,此方法返回一個字串。

我們可以透過執行以下程式來驗證 charAt() 方法在 index 引數超出 0-str.length-1 範圍時返回空字串的事實。

<html>
<head>
<title>JavaScript String charAt() Method</title>
</head>
<body>
<script>
   const str = "JavaScript";
   document.write("str = ", str);
   document.write("<br>str.length = ", str.length);
   let index = 20;
   document.write("<br>index = ", index);
   document.write("<br>The character at index ", index , " is = ", str.charAt(index));
</script>
</body>
</html>

輸出

對於超出範圍的索引值,它將返回空字串,例如 -

str = JavaScript
str.length = 10
index = 20
The character at index 20 is =

示例 4

此示例演示了 charAt() 方法的即時用法。它計算給定字串“Welcome to Tutorials Point”中的空格和單詞。

<html>
<head>
<title>JavaScript String charAt() Method</title>
</head>
<body>
<script>
   const str = "Welcome to Tutorials Point";
   document.write("Given string = ", str);
   let spaces = 0;
   for(let i = 0; i<str.length; i++){
      if(str.charAt(i) == ' '){
         spaces = spaces + 1;
      }
   }
   document.write("<br>Number of spaces = ", spaces);
   document.write("<br>Number of words = ", spaces + 1);
</script>
</body>
</html>

輸出

上述程式計算並返回字串中的空格和單詞數。

Given string = Welcome to Tutorials Point
Number of spaces = 3
Number of words = 4
廣告