简介JavaScript中charAt()方法的使用
这个方法返回从指定索引的字符。
字符串中的字符进行索引从左向右。第一个字符的索引是0,并且在一个叫stringName字符串的最后一个字符的索引是
stringName.length-1。
语法
string.charAt(index);
| 参数 | 描述 |
|---|---|
| index | 必需。表示字符串中某个位置的数字,即字符在字符串中的下标。 |
下面是参数的详细信息:
- index:介于0和1比串的长度以下的整数。
返回值:
返回从指定索引的字符。
提示和注释
注释:字符串中第一个字符的下标是0。如果参数index不在0与string.length之间,该方法将返回一个空字符串。
实例
在字符串"Helloworld!"中,我们将返回位置1的字符:
<scripttype="text/javascript"> varstr="Helloworld!" document.write(str.charAt(1)) </script>
以上代码的输出是:
e
例子:
<html>
<head>
<title>JavaScriptStringcharAt()Method</title>
</head>
<body>
<scripttype="text/javascript">
varstr=newString("Thisisstring");
document.writeln("str.charAt(0)is:"+str.charAt(0));
document.writeln("<br/>str.charAt(1)is:"+str.charAt(1));
document.writeln("<br/>str.charAt(2)is:"+str.charAt(2));
document.writeln("<br/>str.charAt(3)is:"+str.charAt(3));
document.writeln("<br/>str.charAt(4)is:"+str.charAt(4));
document.writeln("<br/>str.charAt(5)is:"+str.charAt(5));
</script>
</body>
</html>
这将产生以下结果:
str.charAt(0)is:T str.charAt(1)is:h str.charAt(2)is:i str.charAt(3)is:s str.charAt(4)is: str.charAt(5)is:i