728x90
반응형
indexOf() / lastIndexOf()
자바스크립트에서 특정 문자의 위치를 찾기위해서 indexOf() / lastIndexOf()를 사용할 수 있습니다.
indexOf() 사용법
"문자열".indexOf(검색값)
"문자열".indexOf(검색값, 위치값)
indexOf()
const str1 = "javascript reference";
const currentStr1 = str1.indexOf("javascript");
const currentStr2 = str1.indexOf("reference");
const currentStr3 = str1.indexOf("j");
const currentStr4 = str1.indexOf("a");
const currentStr5 = str1.indexOf("v");
const currentStr6 = str1.indexOf("jquery");
const currentStr7 = str1.indexOf("b");
const currentStr8 = str1.indexOf("javascript", 0);
const currentStr9 = str1.indexOf("javascript", 1);
const currentStr10 = str1.indexOf("reference", 0);
const currentStr11 = str1.indexOf("reference", 1);
const currentStr12 = str1.indexOf("reference", 11);
const currentStr13 = str1.indexOf("reference", 12);
결과보기
const currentStr4 = str1.indexOf("a");
중복되는 문자가 있을 경우, 가장 먼저 위치 하는 값이 출력 됩니다.
const currentStr6 = str1.indexOf("jquery");
데이터가 없을 경우에는 -1이 출력 됩니다.
lastIndexOf()
lastIndexOf()는 뒤에서 부터 특정 문자를 찾습니다.
"문자열".lastIndexOf(검색값)
"문자열".lastIndexOf(검색값, 위치값)
const currentStr14 = str1.lastIndexOf("javascript");
const currentStr15 = str1.lastIndexOf("reference");
const currentStr16 = str1.lastIndexOf("j");
const currentStr17 = str1.lastIndexOf("a");
const currentStr18 = str1.lastIndexOf("v");
const currentStr19 = str1.lastIndexOf("jquery");
const currentStr20 = str1.lastIndexOf("b");
const currentStr21 = str1.lastIndexOf("javascript", 0);
const currentStr22 = str1.lastIndexOf("javascript", 1);
const currentStr23 = str1.lastIndexOf("reference", 0);
const currentStr24 = str1.lastIndexOf("reference", 1);
const currentStr25 = str1.lastIndexOf("reference", 11);
const currentStr26 = str1.lastIndexOf("reference", 12);
결과보기
'JavaScript' 카테고리의 다른 글
정규표현식 (4) | 2022.08.16 |
---|---|
slice() / substring() / substr() (4) | 2022.08.16 |
내장 함수 (3) | 2022.08.13 |
배열 객체 - join() / push() / pop() (7) | 2022.08.11 |
요소 선택 (7) | 2022.08.06 |
댓글