JavaScript String charAt() 方法返回一个新字符串,其中包含来自给定索引处的原始字符串的单个字符。索引是字符在字符串中的位置,从第一个字符的 0 开始,到最后一个字符的 n-1 结束,其中 n 是字符串的长度。
注意 − 如果给定的索引值超出 0 到 str.length-1 的范围,则此方法将返回空字符串。它还将空格视为有效字符,并将其包含在输出中。
语法
以下是 JavaScript String charAt() 方法的语法 -
charAt(index)
参数
此方法采用一个名为 'index' 的可选参数,下面将解释 -
- index − 字符的索引(位置)。
返回值
此方法在指定索引处返回一个字符。
示例 1
当我们省略 index 参数时,charAt() 方法会假设其 index 参数默认值为 0,并返回给定字符串 “qikepu” 中的第一个字符 'q'。
<html>
<head>
<title>JavaScript String charAt() Method</title>
</head>
<body>
<script>
const str = "qikepu";
document.write("str = ", str);
document.write("<br>str.charAt() returns = ", str.charAt());
</script>
</body>
</html>
输出
上面的程序返回 defualt index(0) 字符 'q'。
str = qikepu
str.charAt() returns = q
str.charAt() returns = q
示例 2
如果我们将 index 值作为 6 传递给此方法,它将返回一个在指定索引处带有单个字符的新字符串。
以下是 JavaScript String 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
index = 6
The character at index 6 is = W
示例 3
当 index 参数不介于 0 和 str.length-1 之间时,该方法返回空字符串。
我们可以通过执行下面的程序来验证如果 index 参数超出 0-str.length-1 的范围,charAt() 方法会返回一个空字符串。
<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 =
str.length = 10
index = 20
The character at index 20 is =
示例 4
此示例演示了 charAt() 方法的实时用法。它计算给定字符串 “Welcome to qikepu” 中的空格和单词。
<html>
<head>
<title>JavaScript String charAt() Method</title>
</head>
<body>
<script>
const str = "Welcome to qikepu";
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 qikepu
Number of spaces = 3
Number of words = 4
Number of spaces = 3
Number of words = 4