본문 바로가기
Javascript

indexOf() / lastIndexOf()

by 코터틀 2022. 8. 16.
반응형

문자열 메서드 : 검색 : indexOf() / lastIndexOf()

indexOf('a')인 경우 'a'를 왼쪽 문자부터 검색하여 일치하는 index 번호를 반환합니다.
일치하는 문자가 없으면 -1을 반환합니다.
indexOf() 메서드는 대소문자를 구분합니다.
lastIndexOf() 메서드는 주어진 값과 일치하는 부분을 fromIndex 로부터 역순으로 탐색하여, 최초로 마주치는 인덱스를 반환합니다.

"문자열".indexOf(검색값);
"문자열".indexOf(검색값, 위치값);
"문자열".lastIndexOf(검색값);
"문자열".lastIndexOf(검색값, 위치값);
const str1 = "javascript reference";

const currentStr1 = str1.indexOf("javascript");     //0 : 문자가 0번째에 위치함
const currentStr2 = str1.indexOf("reference");     //11 : 문자가 11번째에 위치함
const currentStr3 = str1.indexOf("j");     //0
const currentStr4 = str1.indexOf("a");     //1
const currentStr5 = str1.indexOf("v");     //2
const currentStr6 = str1.indexOf("jquery");     //-1 : 데이터가 없을 때
const currentStr7 = str1.indexOf("b");     //-1 : 데이터가 없을 때
const currentStr8 = str1.indexOf("javascript", 0);     //0
const currentStr9 = str1.indexOf("javascript", 1);     //-1
const currentStr10 = str1.indexOf("reference", 0);     //11
const currentStr11 = str1.indexOf("reference", 1);     //11
const currentStr12 = str1.indexOf("reference", 11);     //11
const currentStr13 = str1.indexOf("reference", 12);     //-1

const currentStr14 = str1.lastIndexOf("javascript");        //0
const currentStr15 = str1.lastIndexOf("reference");        //11
const currentStr16 = str1.lastIndexOf("j");        //0
const currentStr17 = str1.lastIndexOf("a");        //3
const currentStr18 = str1.lastIndexOf("v");        //2
const currentStr19 = str1.lastIndexOf("jquery");        //-1
const currentStr20 = str1.lastIndexOf("b");        //-1
const currentStr21 = str1.lastIndexOf("javascript", 0);      //0
const currentStr22 = str1.lastIndexOf("javascript", 1);      //0
const currentStr23 = str1.lastIndexOf("reference", 0);      //-1
const currentStr24 = str1.lastIndexOf("reference", 1);      //-1
const currentStr25 = str1.lastIndexOf("reference", 11);     //11
const currentStr26 = str1.lastIndexOf("reference", 12);     //11

indexOf() 예제

아래 예제는 "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'));
// 첫번째 w 문자 위치는 8
console.log('The index of the first w from the end is ' + anyString.lastIndexOf('w'));
// 마지막 w 문자 위치는 10

console.log('The index of "new" from the beginning is ' + anyString.indexOf('new'));
// 첫번째 new 문자열 위치는 6
console.log('The index of "new" from the end is ' + anyString.lastIndexOf('new'));
// 마지막 new 문자열 위치는 6
반응형

'Javascript' 카테고리의 다른 글

정규표현식  (10) 2022.08.16
slice() / substring() / substr()  (12) 2022.08.16
내장 함수  (6) 2022.08.15
배열 메서드  (9) 2022.08.11
요소 선택  (7) 2022.08.06

댓글


광고 준비중입니다.