SQL PHP HTML ASP JavaScript articles and free scripts to download
JavaScript String

indexOf & lastIndexOf to get location of a string

We can find out the location of a particular string inside the main string by using indexOf function. This is some what opposite of the charAt function which returns the char once a location is given. By using indexOf function we can find out the location and this function returns a number. The first character of the main string is considered as 0 location. Here is an example of indexOf function.

<script type="text/javascript">
var my_str="Welcome to www.plus2net.com"
document.write(my_str.indexOf("plus"))
</script>

The above code will return 15

lastIndexOf

This function returns the position of string by checking from end or right side of the string. This way we can find out the last occurrence of the string from the left but the location is given from right side.

Here is the code.

var my_str="Welcome to www.plus2net.com"
document.write(my_str.lastIndexOf("l"))

Output of above code is 16 as l position is counted from left side but this is the last occurrence of l

Google+

Post Comment This is for short comments only. Use the forum for more discussions.
Name
Email( not to be displayed)Privacy Policy
1+2=This is to prevent automatic submission by spammers. Please enter the result of the sum as asked




HTML . MySQL. PHP. JavaScript. ASP. Photoshop. Articles. FORUM Contact us

©2000-2014 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer