본문 바로가기

코딩/Javascript

자바스크립트 - String에서 특정 문자 찾기 (charAt() 함수)

반응형

 

const str = 'hello world';
console.log(str.charAt(4)); // o
console.log(str[4]); // o

'hello world'이라는 String에서 5번째 문자를 찾으려고 str.charAt(4)라고 실행했다.

str[4]로도 동일한 결과가 나온다 왜나하면 StringArray의 한 종류이기 때문에 대괄호로 특정 값 접근이 가능하다.

 

 

str[] VS str.charAt() 차이점 1

const arr = ['1', '2', '3'];
const obj = { name: 'John', age: 12 };

console.log(arr.charAt(1)) // TypeError: arr.charAt is not a function
console.log(obj.charAt(1)) // TypeError: obj.charAt is not a function

charAt() 함수는 String에만 쓸 수 있는 함수이다.

 

 

 

str[] VS str.charAt() 차이점 2

console.log(str.charAt(-1)); //
console.log(str.charAt(100)); //

charAt() 함수 사용 시, 인덱스 범위가 String의 길이 범위를 벗어나도 아무런 아웃풋이 없다.

 

 

console.log(str[-1]); // undefined
console.log(str[100]); // undefined

대괄호로 특정 값 접근 시, 인덱스 범위가 String의 길이 범위를 벗어나면 아웃풋이 undefined이다.

반응형