• Now Online : 15
  • admin@codemyne.net

Introduction

Sometimes we need to search for a string within another string. For example, we may want to find whether an e-mail address contains an @ character or a URL contains www.

JavaScript offers two methods that can be used in those situations: indexOf() and lastIndexOf() .

The indexOf() method accepts a string to be searched within another string and then returns the start position of the first occurrence of that string. The position starts from 0.

The lastIndexOf() method is similar to indexOf(), but it searches for the last occurrence of a given string. Both these methods return -1 if the specified string cannot be found. The following code shows how they are used:

var url="http://www.codemyne.com";
var result=url.indexOf("www");
alert(result);
result = url.lastIndexOf(".");
alert(result);

The first line of the code creates a variable named url and stores a URL string in it. The indexOf() method is then called on the url to search www. The return value of indexOf() is stored in the variable result. An alert() displays the result to the user. In this example, indexOf() returns 7 because www begins at the seventh position (positioning starts from 0).

Next, the lastIndexOf() method is called on the url variable to find out the last occurrence of a dot. In this case, the result is 22 because the last dot is found just before com.

Comments/Suggestions are invited. Happy coding......!

Comments Post a Comment