Home  >  Article  >  Web Front-end  >  Usage examples of js charAt_javascript skills

Usage examples of js charAt_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:59:281385browse

eg:

Copy code The code is as follows:








Result:

The first character is: H
The second character is: e
The third character is: l

Definition and usage

charAt( ) method returns the character at the specified position.

Note that JavaScript does not have a character data type distinct from the string type, so the characters returned are strings of length 1.

Syntax

stringObject.charAt(index)

Parameter Description

index Required. A number that represents a certain position in a string, that is, the subscript of a character in the string.

Tips and Notes

Note: The index of the first character in the string is 0. If the parameter index is not between 0 and string.length, this method returns an empty string.

Example

In the string "Hello world!", we will return the character at position 1:
Copy code The code is as follows:



The output of the above code is:

e

Return the specified The character at index position.

strObj.charAt(index)

Parameters

strObj

Required. Any String object or literal.

index

Required. The zero-based index of the desired character. Valid values ​​are between 0 and the string length minus 1.

Description

The charAt method returns a character value that is located at the specified index position. The first character in the string has index 0, the second has index 1, and so on. Index values ​​outside the valid range return an empty string.

Example

The following example illustrates the use of the charAt method:
Copy code Code As follows:

function charAtTest(n){
var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // Initialize variables.
var s; // Declare variables.
s = str.charAt(n - 1); // Get the correct character from index n - 1
//
return(s); //Return characters.
}
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