본문 바로가기
JavaScript

indexOf() | lastindexOf()

by SyuMay 2022. 8. 16.
728x90

indexOf() | lastindexOf()

문자열에서 특정 문자의 위치를 찾고 숫자를 반환합니다.

"문자열".indexOf(검색값)
"문자열".indexOf(검색값, 위치값)
만약 하나의 문자가아닌 여러개의 문자라면, 일치하는 값의 첫번째 위치값을 알려줍니다.
또한 검색값에 음수를 사용하면 뒤에서 부터 찾습니다.
"문자열".lastindexOf(검색값)
"문자열".lastindexOf(검색값, 위치값)


const str1 = "javascript reference"
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
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
728x90
반응형

'JavaScript' 카테고리의 다른 글

toLowerCase() | toLowerCase()  (2) 2022.08.17
trim()  (2) 2022.08.17
slice() | substring() | substr()  (7) 2022.08.16
정규식 표현  (6) 2022.08.16
내장 함수  (4) 2022.08.15

댓글


자바스크립트 사진

JavaScript

자세히보기