Home  >  Article  >  Web Front-end  >  Detailed explanation of the use of charCodeAt() method in JavaSacript_Basic knowledge

Detailed explanation of the use of charCodeAt() method in JavaSacript_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 15:56:161558browse

This method returns a number representing the Unicode value of the character at the given index.

Unicode code points range from 0 to 1114111. A direct match of the ASCII character encoding of the first 128 Unicode code points. charCodeAt() will always return a value less than 65,536.
Grammar

string.charCodeAt(index);

Here are the details of the parameters:

  • index: an integer between 0 and 1 that is less than the length of the string; defaults to 0 if not specified.

Return value:

Returns a number representing the Unicode value of the character at the given index. If the given index is not a length between 0 and 1, NaN is returned.
Example:

<html>
<head>
<title>JavaScript String charCodeAt() Method</title>
</head>
<body>
<script type="text/javascript">
var str = new String( "This is string" );
document.write("str.charCodeAt(0) is:" + str.charCodeAt(0)); 
document.write("<br />str.charCodeAt(1) is:" + str.charCodeAt(1)); 
document.write("<br />str.charCodeAt(2) is:" + str.charCodeAt(2)); 
document.write("<br />str.charCodeAt(3) is:" + str.charCodeAt(3)); 
document.write("<br />str.charCodeAt(4) is:" + str.charCodeAt(4)); 
document.write("<br />str.charCodeAt(5) is:" + str.charCodeAt(5)); 
</script>
</body>
</html>

This will produce the following results:

str.charCodeAt(0) is:84
str.charCodeAt(1) is:104
str.charCodeAt(2) is:105
str.charCodeAt(3) is:115
str.charCodeAt(4) is:32
str.charCodeAt(5) is:105 

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn