문자열 내에 있는 문자들은 좌 -> 우 방향으로 순번이 매겨진다. 첫번째는 0번째 순번(index)이며, 문자열의 마지막 문자의 순번은 (인덱스 총 수 -1) 이다.
const paragraph = We’re proud of our safety heritage. We’ll keep innovating safety to help you protect what's important.';
const searchTerm = 'safety';
const indexOfFirst = paragraph.indexOf(searchTerm);
console.log(`The index of the first "${searchTerms}" from the beginnging is ${indexOfFrist}`);
// expected output : The index of the first "safety" from the beginnging is 20
console.log(`The index of the 2nd "${searchTerm}" is ${paragraph.indexOf(searchTerm, (indexOfFirst + 1))}`);
// expected output : The index of the 2nd "safety" is 59
문법
string.indexOf(searchValue[, fromIndex])
( 위의 예시에서는 const indexOfFirst = paragraph.indexOf(searchTerm); )
매개변수
searchValue : 찾으려는 문자열. ( 아무값이 주어지지 않은 경우 문자열 "undifined"를 찾으려는 문자열로 사용 )
fromIndex : 문자열에서 찾기 시작하는 위치를 나타내는 인덱스 값
반환값
searchValue의 첫번째 등장 인덱스. 찾을 수 없으면 -1
'Blue moon'.indexOf('Blue') !== -1; //true
'Blue moon'.indexOf('Blie') !== -1; //false
'blue moon'.indexOf('Blue') !== -1; //false( 대소문자를 구별함을 알 수 있다. )
'0'을 평가했을 때 true가 아니고, -1을 평가했을 때 false 가 아닌 것에 주의해야 한다.
indexOf()는 대소문자를 구별한다.
var str = 'To be, or not to be, that is the question.';
var count = 0;
var pos = str.indexOf('e'); //이때 pos는 4의 값을 가진다
while (pos !== -1) {
count++;
pos = str.indexOf('e',pos +1); // 첫번째 e 이후의 인덱스부터 e 를 찾는다
}
console.log(count);
// expexted output : 4