728x90
문자열 메서드 : indexOf() / lastIndexOf()
문자열 메서드를 활용하면 원하는 문자가 포함된 문자열을 찾을 수 있습니다. 문자의 검색이 가능한 indexOf() 메서드를 잘 알아두었다가 활용합시다.
> indexOf() / lastIndexOf() 메서드
indexOf() / lastIndexOf() 메서드는 괄호()안에 검색값을 작성해 검색값이 문자열의 몇번 째 자리에 위치한지 알 수 있습니다. 해당 검색값이 자리한 위치값을 숫자로 반환합니다. indexOf() 메서드는 맨 앞부터, lastIndexOf() 메서드는 문자열의 맨 뒤부터 시작합니다.
"문자열".indexOf("검색값")
"문자열".indexOf("검색값", "위치값")
"문자열".lastIndexOf("검색값")
"문자열".lastIndexOf("검색값", "위치값")
"문자열".indexOf("검색값", "위치값")
"문자열".lastIndexOf("검색값")
"문자열".lastIndexOf("검색값", "위치값")
번호 | 기본값 | 메서드 | 리턴값 |
---|---|---|---|
1 | "javascript reference" | indexOf("javascript") | 0 |
2 | "javascript reference" | indexOf("reference") | 11 |
3 | "javascript reference" | indexOf("a") | 1 |
4 | "javascript reference" | indexOf("jquery") | -1 |
5 | "javascript reference" | indexOf("javascript", 0) | 0 |
6 | "javascript reference" | indexOf("javascript", 1) | -1 |
7 | "javascript reference" | indexOf("reference", 1) | 11 |
6 | "javascript reference" | ("reference", 11) | 11 |
const str1 = "javascript reference";
//indexOf()
const currentStr1 = str1.indexOf("javascript"); // 0
const currentStr2 = str1.indexOf("reference"); // 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 : 데이터가 없을 땐 -1
const currentStr7 = str1.indexOf("b"); // -1 : 데이터가 없을 땐 -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
//lastIndexOf()
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
728x90
'Javascript' 카테고리의 다른 글
문자열 메서드 : concat() (4) | 2022.08.17 |
---|---|
문자열 메서드 : replace() / replaceAll() (3) | 2022.08.17 |
문자열 메서드 : slice() / substring() / substr() (5) | 2022.08.16 |
정규식 표현 알아보기 (5) | 2022.08.16 |
내장 함수 알아보기 (5) | 2022.08.13 |
댓글