Example of getting started with the charAt method of a JavaScript string object (used to obtain characters at a specified position), including javascriptcharat

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.