lastIndexOf() 메서드는 String 오브젝트에서 fromIndex로부터 반대방향으로 찾기 시작하여 특정 값이 일치하는 마지막 인덱스를 반환합니다. 문자열에서 일치하는 특정 값이 없으면 -1을 리턴합니다.
문법
str.lastIndexOf(searchValue[, fromIndex])
파라미터들
searchValue- 찾고자 하는 문자열입니다. 만약
searchValue를 공백으로 입력하면,fromIndex값을 반환합니다. fromIndexOptional- 문자열에서 반대방향으로 찾고자 하는 시작 인덱스입니다. 아무 정수나 가능합니다. 기본값은 문자열 전체 길이인
str.length-1이라서 기본적으로 전체 문자열을 모두 검색하게 됩니다. 만약fromIndex >= str.length이면, 전체 문자열에 대해 검색하게 됩니다. 만약fromIndex < 0으면, 0을 입력한 것과 동일하게 동작합니다.
설명
문자열에 있는 문자들은 왼쪽에서 오른쪽으로 인덱스(순번)이 매겨집니다. 첫 번째 문자의 인덱스는 0이며, 마지막 문자의 인덱스는 str.length -1 입니다.
'canal'.lastIndexOf('a'); // returns 3
'canal'.lastIndexOf('a', 2); // returns 1
'canal'.lastIndexOf('a', 0); // returns -1
'canal'.lastIndexOf('x'); // returns -1
'canal'.lastIndexOf('c', -5); // returns 0
'canal'.lastIndexOf('c', 0); // returns 0
'canal'.lastIndexOf(''); // returns 5
'canal'.lastIndexOf('', 2); // returns 2
대소문자 구분
The lastIndexOf() 메서드는 대소문자를 구분합니다. 예를 들어, 아래 예제는 일치하는 문자열이 없어 -1 값을 반환합니다:
'Blue Whale, Killer Whale'.lastIndexOf('blue'); // returns -1
예제
indexOf()와 lastIndexOf() 사용하기
아래 예제는 "Brave new world" 문자열의 위치를 확인하기 위해 indexOf()와 lastIndexOf()를 사용하고 있습니다.
var anyString = 'Brave new world';
console.log('The index of the first w from the beginning is ' + anyString.indexOf('w'));
// logs 8
console.log('The index of the first w from the end is ' + anyString.lastIndexOf('w'));
// logs 10
console.log('The index of "new" from the beginning is ' + anyString.indexOf('new'));
// logs 6
console.log('The index of "new" from the end is ' + anyString.lastIndexOf('new'));
// logs 6
Specifications
브라우저 호환성
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
| Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |