Examples of indexOf () and lastIndexOf application methods in Javascript, indexoflastindexof

Source: Internet
Author: User

Examples of indexOf () and lastIndexOf application methods in Javascript, indexoflastindexof

IndexOf () method

indexOf() Returns the position of the first occurrence of a specified string value.

Note:indexOf() The method is case sensitive!

Note: If the string value to be retrieved does not appear, this method returns-1.

Use the charAt () method

var str ='www.webclks.com/archives/3309';for(var i=0; i<str.length; i++){ if(str.charAt(i)==='/'){ alert(i); }}

IndexOf () method

Var str = 'www .webclks.com/archives/3309'{alert (str. indexOf ('/'); // query alert (str. indexOf ('/', 16); // query alert (str. indexOf ('x'); // If no result is found,-1 is returned;

IndexOf () Method Instance

Var str = 'focus on script learning, share script learning materials and learning skills! '; Var s =' script; // the content to be queried var I = 0; // The first few queries/* for (; str. indexOf (s, I )! =-1;) {alert (str. indexOf (s, I); I = str. indexOf (s, I) + s. length;} */while (str. indexOf (s, I )! =-1) {alert (str. indexOf (s, I); I = str. indexOf (s, I) + s. length ;}

LastIndexOf () method

lastIndexOf() Method returns the position where a specified string value appears at the end, and searches for the specified position in a string from the back to the front.

Note:lastIndexOf() The method is case sensitive!

Note: If the string value to be retrieved does not appear, this method returns-1.

LastIndexOf ()Method Instance

Var str = 'focus on Web Front-end learning and share Web Front-end learning materials and learning skills! '; Alert (str. indexOf ('w', 0); // query alert (str. lastIndexOf ('w', 24); // query from the back

If the 2nd values are negative, the default value is 0.

Summary

The above is all the content in this article. I hope it will be helpful for everyone's learning work. If you have any questions, please leave a message.

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.