Example of getting started with the charAt method of a JavaScript string object (used to obtain characters at a specified position), including javascriptcharat
JavaScript charAt Method
The charAt method is used to obtain characters at the specified position from a string. The syntax is as follows:
Copy codeThe Code is as follows:
Str_object.charAt (x)
Parameter description:
Parameters |
Description |
Str_object |
String (object) to be operated) |
X |
Required. Number indicating the position |
Tip: the string is counted from 0.
CharAt Method Instance
Copy codeThe Code is as follows:
<Script language = "JavaScript">
Document. write ("jb51". charAt (1 ));
</Script>
Run this example and output:
Copy codeThe Code is as follows:
B
Tip: If the parameter x is not between 0 and the maximum length of the string, this method returns an empty string.
Use javascript to replace characters at a specified position
The above are all incorrect.
Replace will replace each character that meets the conditions. If the original string has multiple identical characters, isn't it all replaced?
In fact, you only need to write a method like this and then call it.
Function replacePos (strObj, pos, replacetext)
{
Var str = strObj. substr (0, pos-1) + replacetext + strObj. substring (pos, strObj. length );
Return str;
}
Var text = "abcdefg"
Var mystr = replacePos (text, 3, "n ");
Mystr = replacePos (mystr, 5, "m ");
The last mystr is the string you want.
Note that the position you want to replace cannot exceed the length of the string.
Otherwise, an error occurs. You can judge in the replacement function. If the length is exceeded, do not replace it.
22) in JavaScript, which of the following statements about the charAt () and indexOf () Methods of String objects is true? (select option 2)
A, B