특정 인덱스와 위치

니나노개발생활·2021년 6월 16일
0
post-thumbnail

특정 인덱스에 위치하는 문자 찾기

1. charAt()

str.charAt(index)

: 주어진 문자열 index 위치의 문자를 찾아서 리턴

  • index는 0부터 시작한다.
  • index가 입력되지 않으면 자동으로 0
let str = 'hello';
str.charAt();     //h
str.charAt(0);    //h
str.charAt(10);   //'' 범위 밖은 공백으로 표출

2. 대괄호

str[index]

: 배열의 index를 가져오듯이 활용

let str = 'hello';
str.[0];     //h
str.[4];     //o
str.[10];    //undefined

특정문자의 인덱스 내 위치찾기

indexOf()

string.indexOf(searchvalue, position)

: 문자열에서 특정 문자를 찾고 검색된 문자열이 '첫번째'로 나타나는 위치 index를 리턴

  • 찾는 문자열이 없으면 -1을 리턴

  • 대소문자 구별

파라미터

  • searchvalue : 찾을 문자열(필수)
  • position : 기본값은 0, searchvalue를 찾기 시작할 위치(옵션)
let str = 'hello';
str.indexOf['ll'];      //2(찾는 문자열의 첫번째 위치)
str.indexOf['lol'];     //-1
str.indexOf['HE'];      //-1

searchvalue 응용하기

let str = 'abcabcabc';
let searchvalue = 'ab;

let pos = 0;
while (true) {
  let foundPos = str.indexOf(searchvalue, pos);
  if (foundPos == -1) break;

  document.writeln( foundPos );
  pos = foundPos + 1; 
}   //0 3 6

반복문 안에서 searchvalue를 찾아 foundPos의 position 값을 다음 index값으로 변경해준다.

참고 블로그

profile
깃헙으로 이사중..

0개의 댓글