[JS] 모던 Javascript Deep Dive 32장 - String
업데이트:
[01] String 생성자 함수
표준 빌트인 객체인 String 객체는 생성자 함수 객체다.
🥕 new 연산자와 함께 호출
const strObj = new String('Lee');
console.log(strObj);
//String {0: "L", 1: "e", 2: "e", length: 3, [[PrimitiveValue]]: "Lee"}
🥕 new 연산자 없이 호출
String(1); // "1"
String(NaN); // "NaN"
[02] length 프로퍼티
문자열의 문자 개수를 반환하는 프로퍼티이다.
인덱스를 나타내는 숫자를 프로퍼티 키로, 인덱스에 해당하는 문자를 프로퍼티 값으로 가지므로 String
은 유사 배열 객체이다.
[03] String 메서드
String은 배열과 다르게 읽기 전용 객체이기 때문에 String 래퍼 객체를 직접 변경할 수는 없고 언제나 새로운 문자열을 생성하여 반환한다.
자주 쓰이는 메서드들을 알아보자 !
String.prototype.indexOf
인수로 전달받은 문자열을 검색하여 첫 번째 인덱스를 반환한다.
const str = 'Hello World';
str.indexOf('l'); // 2
str.indexOf('or'); // 7 (or로 검색했지만 첫번째 인덱스만 반환한다)
str.indexOf('x'); // -1 (검색에 실패하면 -1을 반환한다)
String.prototype.search
정규표현식과 매치하는 문자열을 검색하여 일치하는 문자열의 인덱스를 반환
const str = 'Hello World';
str.search(/o/); // 4
str.search(/x/); // -1
String.prototype.includes
const str = 'Hello World';
str.includes('Hello'); // true
// 인덱스 3부터 d가 포함되었는지 확인
str.includes('d', 3); // true
str.include('H', 3); //false
String.prototype.startsWith
const str = 'Hello World';
//문자열 str이 인수로 시작하는지 확인
str.startWith('He'); // true
str.startWith('x'); // false
//문자열 str의 인덱스 5부터 시작하는 문자열이 ' '로 시작하는지 확인
str.startWith(' ', 5); //true
String.prototype.endsWith
const str = 'Hello World';
//문자열 str이 'ld'로 끝나는지 확인
str.endsWith('ld'); // true
str.endsWith('x'); //false
//문자열 str의 처음부터 5자리까지 'lo'로 끝나는지 확인
str.endsWith('lo', 5) //true
String.prototype.charAt
const str = 'Hello';
// 문자열에서 인수로 전달받은 인덱스에 위치한 문자를 반환
for(let i=0; i < str.length; i++){
console.log(str.charAt(i)); // H e l l o
}
str.charAt(5); // ''
// 문자열의 범위에서 벗어나면 빈 문자열 출력
String.prototype.substring
// 전달받은 두 인수의 인덱스 범위안에 있는 문자열 반환
const str = 'Hello World';
str.substring(1,4); // 'ell'
str.substring(1); // 'ello World'
str.substring(4,1); // 'ell' (첫 번째 인수가 더 커서 교환됨)
str.substring(-2); // 'Hello World'
str.substring(20); // ''
🔍 substring + indexOf
const str = 'Hello World!';
// 스페이스를 기준으로 앞에 있는 문자열 취득
str.substring(0, str.indexOf(' ')); // 'Hello'
// 스페이스를 기준으로 뒤에 있는 문자열 취득
str.substring(str.indexOf(' ')+1, str.length) // 'World'
String.prototype.slice
substring과 동일하게 동작하는데 음수인 인수를 전달했을 때 뒤에서부터 자른다는 차이가 있다.
const str = 'Hello World';
str.slice(0,5); // 'Hello'
str.slice(2); // 'llo World'
str.slice(-5); // 'World'
String.prototype.toUpperCase / toLowerCase
문자열을 모두 대문자로 반환/소문자로 반환
String.prototype.trim
대상 문자열 앞뒤에 공백 문자가 있을 경우 제거한 문자열을 반환
String.prototype.repeat
const str = 'abc';
str.repeat(0); // ''
str.repeat(2); // 'abcabc'
str.repeat(2.5) // 'abcabc'
str.repeat(-1) // RangeError: Invalid count value
String.prototype.replace
const str = 'Hello World';
str.replace('world', 'Lee'); // Hello Lee
// 첫번째 인수를 두번째 인수로 치환한다.
replace 메서드의 첫 번째 인수로 정규 표현식을 전달할 수도 있다.
두 번째 인수로 치환 함수를 전달할 수 있다.
아래 코드는 치환 함수를 전달한 예시이다.
const camelCase = 'helloWorld';
// /.[A-Z]/g => 1문자와 대문자의 조합을 문자열 전체에서 검색한다.
console.log(camelCase.replace(/.[A-Z]/g, function (match) {
// match : oW => match[0] : o, match[1] : W
return match[0] + '_' + match[1].toLowerCase();
})); // hello_world
// /(.)([A-Z])/g => 1문자와 대문자의 조합
// $1 => (.)
// $2 => ([A-Z])
console.log(camelCase.replace(/(.)([A-Z])/g, '$1_$2').toLowerCase()); // hello_world
// snake_case => camelCase
const snakeCase = 'hello_world';
// /_./g => _와 1문자의 조합을 문자열 전체에서 검색한다.
console.log(snakeCase.replace(/_./g, function (match) {
// match : _w => match[1] : w
return match[1].toUpperCase();
})); // helloWorld
✍ 코드를 이해하는 과정에서 .[A-Z]
가 왜 oW가 되는지 이해가 안되었는데 .이 임의의 숫자를 나타낸다는 것을 잊고 있었다. 다시 기억하자 !
String.prototype.split
const str = 'What are you doing?";
str.split(' '); // ["What", "are", "you", "doing?"]
split 문자열을 배열로 바꿀 때 자주 사용하는 메서드이다.
function reverseString(str){
return str.split('').reverse().join('');
}
reverseString('Hello world!'); // '!dlrow olleH'
댓글남기기