indexOf() and lastIndexOf() String methods in Javascript




indexOf() and lastIndexOf() String methods in Javascript

indexOf() Method in Javascript:

The indexOf() method gives the position of the first occurrence of a specified text. Position is counted from 0 in Javacript.
e.g.

<script>
var str = "This is to locate the ball lost - locate it";
var pos = str.indexOf("locate");
console.log(pos);
</script>

This will print 11 in the console as “locate” first occurrence is at 11th position.

lastIndexOf() Method in Javascript:

The lastIndexOf() method gives the position of the last occurrence of a specified text. Position is counted from 0 in Javacript.
e.g.

<script>
var str = "This is to locate the ball lost - locate it";
var pos = str.indexOf("locate");
console.log(pos);
</script>

This will print 34 in the console as “locate” last occurrence is at 34th position.