Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript lastIndexOf() Method

JavaScript lastIndexOf() Method

String Object Reference JavaScript String object

Example

Find the last occurrence position of the string "runoob":

var

str

=

"

I am from runoob, welcome to runoob site.

"

;

var

n

=

str

.

lastIndexOf

(

"

runoob

"

)

;

n Output result:

28

Try it »


Definition and Usage

The lastIndexOf() method returns the last occurrence position of a specified string value. If a second argument start is specified, it searches backward from the specified position in a string.

Note: This method searches the string from back to front, but the returned position of the last substring occurrence is counted from the starting position (0). It checks whether the string contains it.

The search starts at position start in the string or at the end of the string (when start is not specified).

If no matching string is found, it returns -1.

**Note:** The lastIndexOf() method is case-sensitive!

Tip: You can also refer to similar methods indexOf() .


Browser support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

All major browsers support the lastIndexOf() method.


Syntax

string

.lastIndexOf(

searchvalue

,

start

)

Parameter value

Parameters Description
searchvalue Required. Specifies the string value to search for.
start Optional integer parameter. Specifies the position in the string where the search begins. Its valid range is 0 to stringObject.length - 1. If this parameter is omitted, the search starts from the last character of the string.

Return Value

Type Description
Number The last occurrence position of the searched string, returning -1 if no matching string is found.

Technical Details

JavaScript version: 1.0

More examples

Example

Find the last occurrence of the string "runoob" starting from the 20th character:

var

str

=

"

I am from runoob, welcome to runoob site.

"

;

var

n

=

str

.

lastIndexOf

(

"

runoob

"

,

20

)

;

n Output result:

10

Try it »

Example

Find the last occurrence of the string "runoob" by searching backward from the 10th character:

var

str

=

"

I am from runoob, welcome to runoob site.

"

;

var

n

=

str

.

lastIndexOf

(

"

runoob

"

,

9

)

;

n Output result:

-1

Try it »


String Object Reference JavaScript String object