JavaScript charCodeAt() method


JavaScript charCodeAt() Method

Instance

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>

<p id="demo">单击按钮显示字符串的第一个字符的编码。</p>
<button onclick="myFunction()">点我</button>
<script>
function myFunction(){
	var str="HELLO WORLD";
	var n=str.charCodeAt(0);
	document.getElementById("demo").innerHTML=n;
}
</script>

</body>

Run Example»

Click the "Run Example" button to view the online example



Definition and usage

The charCodeAt() method can return the Unicode encoding of the character at the specified position.

The position of the first character in the string is 0, the position of the second character is 1, and so on.


Browser support

QQ截图20161108165429.png

All major browsers support the charCodeAt() method


Syntax

string.charCodeAt(index)

Parameter value

Parameter Description
indexRequired. A number that represents a certain position in a string, that is, the subscript of a character in the string.

Return value

TypeDescription
NumberReturns the Unicode encoding of the character at the specified position.

Technical Details

JavaScript Version: 1.2


More examples

Instances

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>

<p id="demo">单击按钮显示字符串最后一个字符的UNICODE 编码</p>
<button onclick="myFunction()">点我</button>
<script>
function myFunction(){
	var str="HELLO WORLD";
	var n=str.charCodeAt(str.length-1);
	document.getElementById("demo").innerHTML=n;
}
</script>

</body>

Running examples»

Click the "Run Instance" button to view the online instance