1. String Constructor

3. String Method

String 객체의 모든 메소드는 언제나 새로운 문자열을 반환한다. 문자열은 변경 불가능(immutable)한 원시 값이기 때문이다.

3.1 String.prototype.charAt(pos: number): string ES1

// 해당 배열에 있는 문자 출력
const str = 'Hello';

console.log(str.charAt(0)); // H
console.log(str.charAt(1)); // e
console.log(str.charAt(2)); // l
console.log(str.charAt(3)); // l
console.log(str.charAt(4)); // o
// 지정한 index가 범위(0 ~ str.length-1)를 벗어난 경우 빈문자열을 반환한다.
console.log(str.charAt(5)); // ''

3.2 String.prototype.concat(…strings: string[]): string ES3

인수로 전달한 1개 이상의 문자열과 연결하여 새로운 문자열을 반환한다. concat 메소드를 사용하는 것보다는 ++= 할당 연산자를 사용하는 것이 성능상 유리하다.

console.log('Hello '.concat('Lee')); // Hello Lee

3.3 String.prototype.indexOf(searchString: string, fromIndex=0): number ES1

인수로 전달한 문자 또는 문자열을 대상 문자열에서 검색하여 처음 발견된 곳의 index를 반환한다. 발견하지 못한 경우 -1을 반환한다.

const str = 'Hello World';

console.log(str.indexOf('l'));  // 2
console.log(str.indexOf('or')); // 7
console.log(str.indexOf('or' , 8)); // -1

if (str.indexOf('Hello') !== -1) {
  // 문자열 str에 'hello'가 포함되어 있는 경우에 처리할 내용
}

// ES6: String.prototype.includes
if (str.includes('Hello')) {
  // 문자열 str에 'hello'가 포함되어 있는 경우에 처리할 내용
}

3.4 String.prototype.lastIndexOf(searchString: string, fromIndex=this.length-1): number ES1

인수로 전달한 문자 또는 문자열을 대상 문자열에서 검색하여 마지막으로 발견된 곳의 index를 반환한다. 발견하지 못한 경우 -1을 반환한다.

const str = 'Hello World';
//뒤에서 부터 검색함
// 뒤에 5라는 인자를 넣을 경우 4부터 검색함
console.log(str.lastIndexOf('World')); // 6
console.log(str.lastIndexOf('l'));     // 9
console.log(str.lastIndexOf('o', 5));  // 4
console.log(str.lastIndexOf('o', 8));  // 7
console.log(str.lastIndexOf('l', 10)); // 9

3.5 String.prototype.replace(searchValue: string | RegExp, replaceValue: string | replacer: (substring: string, …args: any[]) => string): string): string ES3

첫번째 인수로 전달한 문자열 또는 정규표현식을 대상 문자열에서 검색하여 두번째 인수로 전달한 문자열로 대체한다. 원본 문자열은 변경되지 않고 결과가 반영된 새로운 문자열을 반환한다.

검색된 문자열이 여럿 존재할 경우 첫번째로 검색된 문자열만 대체된다.