써치킴의 우당탕탕 개발 블로그

[JS Level up][Ch1][데이터] 문자 본문

파도파도 나오는 JavaScript

[JS Level up][Ch1][데이터] 문자

써치킴 2022. 1. 28. 20:09

String 

String 전역 객체는 문자열(문자의 나열)의 생성자이다.

 

? 전역 객체 : 자바스크립트 전체 영역에서 쓸 수 있는 객체

? 생성자 <-> 리터럴 방식 (""(따옴표),{},[]와 같이 기호를 통해 객체를 만드는 방식)

 

문자와 관련된 문서가 필요할때!

mdn 문서를 활용

String.prototype

프로토타입을 통해 지정한 메소드는 메모리에 한번만 만들어지고,

그것을 생성자가 new라는 키워드로 만들어낸 인스턴스에서 언제든지 활용할 수 있다.

.indexOf()

String 객체에서 주어진 값과 일치하는 첫 번째 인덱스를 반환, 일치하는 값이 없으면 -1을 반환

// String.prototype.indexOf()
const result = 'Hello world'.indexOf('world');
const resultS = 'Hello world'.indexOf('search');
console.log(result);      // 6
console.log(resultS);     // -1

.length

문자 데이터 안의 글자가 몇개인가?

const str = '0123';   // 문자 데이터
console.log(str);
console.log(str.length);    // 문자 데이터 안의 글자가 몇개인가?

.slice(beginIndex, endIndex)

beginIndex부터 endIndex 직전까지 잘라내어 새로운 문자열로 반환

const strH = 'Hello world';
console.log(strH.slice(0, 3));    // 0번째부터 3번째까지 직전까지 잘라냄
console.log(strH.slice(6));       // 6번째부터 끝까지 잘라냄

.replace()

// 첫번째 인수의 문자를 찾아서 두번째 인수로 바꿔줌
console.log(strH.replace('world', 'searchKim'));    // Hello searchKim
console.log(strH.replace(' world', ''));            // Hello

.match()

정규표현식을 통해 특정 데이터를 매치.

const strM = 'ejkim.Dev@gmail.com';
// 이메일 아이디만 추출
console.log(strM.match(/.+(?=@)/)[0]);   // 정규표현식

.trim()

공백 제거

const strB = '    Hello world   ';
console.log(strB.trim());     // 공백 제거

Comments