JavaScript tutorial-String object indexOf | lastIndexOf

JavaScript String object: indexOf | lastIndexOf

You can use the inexOf(string,[start_index]) or the lastIndexOf(string,[start_index]) to find a string in another string. When the target string is found these methods return 0. In contrast, they return -1. the start_index argument is optional. If you don't specify the start_index argument, the indexOf() method will start to search for the target string from the beginning of another string. The difference between the two method is that the indexOf() method searches from the beginning to the end of a string while the lastIndexOf() methods searches from the last the the beginning of a string. In the example below, we use the indexOf() method to search for "JavaScript" string in the "I like JavaScript." string. The two methods are case-sensitive. Finding the string "JavaScript" and "javascript" in "I like JavaScript." string produces different results.

<title>Using indexOf() method</title>

<script language="JavaScript" type="text/javascript">

var Mystr="I like JavaScript.";
var Targetstr="JavaScript";
if(Mystr.indexOf(Targetstr)>0) document.write("Found!");
else document.write("Not found!");




Lyon comment


That is very good tutorials.


This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.