eg:
<html>

<body>


<script type="text/javascript">


var str="Hello world!"

document.write("The first character is: " + str.charAt(0) + "<br />")

document.write("The second character is: " + str.charAt(1) + "<br />")

document.write("The third character is: " + str.charAt(2))


</script>


</body>

</html>結果:
The first character is: H

The second character is: e

The third character is: l

定義和用法

charAt() 方法可返回指定位置的字符。

請注意,JavaScript 並沒有一種有別於字符串類型的字符數據類型,所以返回的字符是長度為 1 的字符串。

語法

stringObject.charAt(index)

參數

描述

index

必需。表示字符串中某個位置的數字,即字符在字符串中的下標。

提示和註釋

註釋:字符串中第一個字符的下標是 0。如果參數 index 不在 0 與 string.length 之間,該方法將返回一個空字符串。

實例

在字符串 "Hello world!" 中,我們將返回位置 1 的字符:

<script type="text/javascript"> var str="Hello world!" document.write(str.charAt(1)) </script>

以上代碼的輸出是:

e


返回指定索引位置處的字符。

strObj.charAt(index)

參數

strObj

必選項。任意 String 對象或文字。

index

必選項。想得到的字符的基於零的索引。有效值是 0 與字符串長度減 1 之間的值。

説明

charAt 方法返回一個字符值,該字符位於指定索引位置。字符串中的第一個字符的索引為 0,第二個的索引為 1,等等。超出有效範圍的索引值返回空字符串。

示例

下面的示例説明了 charAt 方法的用法:

function charAtTest(n){
   var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // 
var s;                                  // 
s = str.charAt(n - 1);                  // 
n – 1
                                           // 
return(s);                              //