01 String 함수: indexOf() 와 lastIndexOf()

filoscoder·2019년 10월 18일
0

Javascript: string

목록 보기
3/3
post-thumbnail

문자열에서 문자(열) 찾기

본 포스팅에서 소개할 함수들의 기본적인 목적은 문자열, 즉, string 타입 안에서 특정 문자 또는 문자열의 위치를 찾아주는 유용하고 기본적인 함수들이다.

위치라고 하면 position을 기리키는 것이다.
Javascript는 zero based 언어이기에
0: 첫번째
1: 두번째
2: 세번째
n: (n+1)번째
...

함수: String.indexOf()

주어진 문자열 str 앞에서부터 (index: 0) 지정한 searchValue가 처음으로 발견되는 위치의 index 반환한다.

문법 (Syntax)

*str*.indexOf(*searchValue*[, *fromIndex*])

매개변수 (Parameter)

  • searchValue

찾고자 하는 문자 또는 문자열 (대소문자 중요). 정확한 string 형식이 아니라면 undefined로 간주하고 이것을 기준 문자열 str에서 찾아 볼 것이다.

  • fromIndex || Optional

integer, 즉 숫자 형식으로 검색을 시작할 index로 기준을 지정해줄 수 있다.
만약 이값이 0 보다 낮고(음수) 그리고 str.length 문자열의 길이보다 높다면, 본 함수는 단순히 str 전체를 검색할 것이다.

반환 (Return)

str에서 searchValue0부터 시작하여 처음으로 검색되는 index 값을 반환한다.
만약, searchValue가 존재하지 않는다면 -1를 반환한다.발견하지 못하면 -1을 반환한다.

예제

let myStr = 'hello wide world!'; // length: 17
let myCapStr = 'Hello Wide world!'; // length: 17

console.log(myStr.indexOf("W"));
// output>  -1
console.log(myStr.indexOf("w"));
// output>  6
console.log(myCapStr.indexOf("w"));
// output>  11

indexOf() 활용 사례

다음 예제는 str 문자열에서 searchValue 문자가 몇번 포함되어 있는지 count 변수에 반환하는 프로그램이다.
indexOf함수의 두번째 매개변수인 fromIndex의 장점을 활용한 것이다.

const str = 'To be, or not to be, that is the question.';
let searchValue = 'e'
let count = 0;
let fromIndex = str.indexOf(searchValue);

while (fromIndex !== -1) {
  count++;
  fromIndex = str.indexOf(searchValue, fromIndex + 1);
}

console.log(count); 
// output>  4

함수: String.lastIndexOf()

주어진 문자열 str 뒤에서부터 (index: 0) 지정한 searchValue가 처음으로 발견되는 위치의 index 반환한다. 발견하지 못하면 -1을 반환한다.

문법 (Syntax)

*str*.lastIndexOf(*searchValue*[, *fromIndex*])

매개변수 (Parameter)

  • searchValue

찾고자 하는 문자 또는 문자열 (대소문자 중요). 정확한 string 형식이 아니라면 undefined로 간주하고 이것을 기준 문자열 str에서 찾아 볼 것이다.

  • fromIndex || Optional

integer, 즉 숫자 형식으로 검색을 시작할 index로 기준을 지정해줄 수 있다.
만약 이값이 0 보다 낮고(음수) 그리고 str.length 문자열의 길이보다 높다면, 본 함수는 단순히 str 전체를 검색할 것이다.

반환 (Return)

str에서 searchValue가 마지막으로 검색되는 index 값을 반환한다.
만약, searchValue가 존재하지 않는다면 -1를 반환한다.

예제

다음 예제는 indexOf()lastIndexOf() 함수를 사용해 각각의 차이를 들어내기 위함이다.

let str = 'Brave new world';

console.log('The index of the first w from the beginning is ' + str.indexOf('w'));
// output>  8
console.log('The index of the first w from the end is ' + str.lastIndexOf('w')); 
// output>  10
console.log('The index of "new" from the beginning is ' + str.indexOf('new'));
// output>  6
console.log('The index of "new" from the end is ' + str.lastIndexOf('new'));
// output>  6

숙제

indexOf() 와 매우 흡사한 search()함수... 차이는???

indexOf()lastIndexOf() 함수와 반대되는 return값은 무엇일까???

profile
Keep thinking code should be altruistic

0개의 댓글