Example of js charAt usage
This article mainly introduces how to use js charAt. For more information, see
Eg:
The Code is as follows:
<Html>
<Body>
<Script type = "text/javascript">
Var str = "Hello world! "
Document. write ("The first character is:" + str. charAt (0) + "<br/> ")
Document. write ("The second character is:" + str. charAt (1) + "<br/> ")
Document. write ("The third character is:" + str. charAt (2 ))
</Script>
</Body>
</Html>
Result:
The first character is: H
The second character is: e
The third character is: l
Definition and usage
The charAt () method returns characters at a specified position.
Note that JavaScript does not have a character data type different from the string type, so the returned character is a string with a length of 1.
Syntax
StringObject. charAt (index)
Parameter description
Index is required. Represents the number at a certain position in the string, that is, the subscript of the character in the string.
Tips and comments
Note: The subscript of the first character in the string is 0. If the index parameter is not between 0 and string. length, this method returns an empty string.
Instance
In the string "Hello world! ", We will return the character at location 1:
The Code is as follows:
<Script type = "text/javascript">
Var str = "Hello world! "
Document. write (str. charAt (1 ))
</Script>
The output of the above Code is:
E
Returns the characters at the specified index position.
StrObj. charAt (index)
Parameters
StrObj
Required. Any String object or text.
Index
Required. Returns the zero-based index of the expected characters. The valid value is the value between 0 and the string length minus 1.
Description
The charAt method returns a character value at the specified index position. The index of the first character in the string is 0, the index of the second character is 1, and so on. If the index value exceeds the valid range, an empty string is returned.
Example
The following example illustrates the usage of the charAt method:
The Code is as follows:
Function charAtTest (n ){
Var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // initialize the variable.
Var s; // name variable.
S = str. charAt (n-1); // from the position where the index is n-1
// Obtain the correct characters.
Return (s); // The return character.
}