// 문자열 심화

 

1. 대소문자 변환

// toUpperCase(), toLowerCase()
// toUpperCase()
const str = 'hello js';
console.log(str.toUpperCase()); // HELLO JS

// toLowerCase()
const str = 'HELLO JS';
console.log(str.toLowerCase()); // hello js

 

2. 공백 제거

// 공백 제거 : trim()
// 공백 앞 제거: trimStart() === trimLeft()
// 공백 뒤 제거: trimEnd() === trimRight()
// 공백 제거 : trim()
const str = '          hi ';
console.log(str.trim()); // hi

// trimStart() === trimLeft()
const str = '      Seize the day ! ';
console.log(str.trimStart()); // Seize the day ! 

// trimEnd() === trimRight()
const str = '      Seize the day ! ';
console.log(str.trimEnd()); //       Seize the day !

 

3. 새로운 문자열 생성

// repeat(n) : n만큼 문자열 반복, 새로운 문자열 반환한다.
새로운 문자열을 반환한다 => 원본 객체는 변하지 않는다.
 
// padStart() padEnd : 문자열의 시작 부분, 끝나는 부분부터 주어진 str을 추가해
지정한 길이를 만족하는 새로운 문자열을 반환
// str.repeat()
const a = 'js';
console.log(a.repeat(3)); // jsjsjs, 원본 객체 a는 변하지 않음!!

// .padStart(n, 'str'), .padEnd(n, 'str')

console.log(a.padStart(5, 'v').padEnd(8, 'v')); // vvvjsvvv

 

4. 문자열 검색 

// indexOf()
키워드를 문자열에서 검색 > 일치하는 1번째 인덱스를 반환, 일치하는 값을 찾지 못하면 -1 반환  

 

// includes()
주어진 키워드 값을 문자열에서 검색 > 값이 있으면 t 없으면 f
// indexOf() 
const str = '안녕하세요. 잘부탁드립니다.';
console.log(str.indexOf('녕')); // 1


// includes()
console.log(str.includes('안')); // t
console.log(str.includes('라')); // f

 

// startsWith('str'), endsWith('str')
// 문자열이 'str'로 시작하는지 여부, 'str'로 끝나는지 여부를 t f 로 반환한다.
 

5. 문자열 수정 

// replace()
주어진 패턴과 일치하는 첫번째 부분을 주어진 문자열로 교체한 새로운 문자열을 반환한다.
 
// replaceAll()
주어진 패턴과 일치하는 모든 부분을 교체 새로운 문자열 반환
// replace
const str = 'What are you doing now?';
str.replace('you', 'we'); // 'What are we doing now?'

 

 

// substring(0, 5)
인덱스 0~4까지 새로운 문자열로 반환
 
// slice()
문자열을 해당위치의 인덱스부터 잘라 새로운 문자열로 반환  
// 시작 인자 == 필수, 종료인자 == 선택

 

// split()
문자열을 주어진 구분자를 기준으로 자른 뒤 그 결과를 배열로 반환한다.

 

// const str = 'What are you';
// str.split(' ');
// ['What', 'are', 'you']
 
 

※ 자바스크립트 독학백서 정리 

 

+ Recent posts