[Javascript] 문자(string)

메타몽·2023년 10월 17일

String(문자)

💡String

전역 객체(자바스크립트의 전체 영역에서 쓸 수 있는) 문자열(문자 데이터)의 생성자



자주 사용하는 메서드


String.prototype.indexOf()

index of()메서드는 호출한 string 객체에서 주어진 값과 일치하는 첫 번째 인덱스를 반환한다.
일치하는 값이 없으면 -1을 반환한다.


+).prototype을 통해 지정한 메소드는 메모리에 딱 한번만 만들어지고, 생성자가 new 라는 키워드로 만들어내는 인스턴스에서 언제든지 활용할 수 있다.

const result = 'Hello world'.indexOf('world');
console.log(result1);
// 6 반환

const result = 'Hello world'.indexOf('maetamong');
console.log(result2);
// -1 반환

//불린데이터로 확인
const str = 'Hello wolrd';
console.log(str.indexOf('maetamong') !== -1);
// false 반환


String.prototype.slice()

slice메소드는 문자열의 begin부터 end까지(end 미포함) 반환한다.

const str = 'Hello world!';
console.log(str.slice(6, 11));
// world

beginIndex 추출 시작점인 0부터 시작하는 인덱스
endIndex 0부터 시작하는 추출 종료점 인덱스로 그 직전까지 추출된다.



String.prototype.replace()

문자열에서 특정 패턴을 검색해 다른 문자열로 교체할 수 있다.

const str = 'Hello world!';
console.log(str.replace('world', 'maetamong'));
// Hello maetamong!


String.prototype.match()

문자열이 정규식과 매치되는 부분을 검색한다.

const str = 'maetamong@gmail.com';

console.log(str.match(/.+(?=@)/));

배열데이터의 첫 번째 아이템으로 @를 포함한 주소가 배제된 결과물을 확인할 수 있다.

const str = 'maetamong@gmail.com';

console.log(str.match(/.+(?=@)/)[0]);
// maetamong

앞쪽의 첫 번째 아이템[0]인 maetamong만 콘솔에 깔끔하게 찍힌다.



String.prototype.trim()

문자열 양 끝의 공백을 제거한 뒤 원본 문자열을 수정하지 않고 새로운 문자열을 반환한다.

const str = '       Hello world    ';
console.log(str);
//       Hello world    
console.log(str.trim());
// Hello world
profile
내가보려고만든벨로그

0개의 댓글