문자열이 불변성을 가지기 때문에 String 객체의 메서드들은 기존 문자열을 변경하지 않고, 새로운 문자열을 반환합니다.
3.1 String.prototype.charAt(pos: number): string ES1 인수로 전달한 index를 사용하여 해당 위치의 문자를 반환한다.
지정한 index가 문자열의 범위(0 ~ (문자열 길이 - 1))를 벗어난 경우 빈문자열을 반환한다.
conststr='Hello';
console.log(str.charAt(0)); // H
console.log(str.charAt(1)); // e
console.log(str[0]); // H
// 지정한 index가 범위(0 ~ str.length-1)를 벗어난 경우 빈문자열을 반환한다.
console.log(str.charAt(5)); // ''
3.2 String.prototype.concat(…strings: string[]): string ES3 인수로 전달한 1개 이상의 문자열과 연결하여 새로운 문자열을 반환한다. concat 메소드를 사용하는 것보다는 +, += 할당 연산자를 사용하는 것이 성능상 유리하다.
// str.concat(str1[,str2,...,strN])
console.log('Hello '.concat('Lee',', ','Kim')); // Hello Lee, Kim
console.log('Hello '+'Lee'+', '+'Kim') // Hello Lee, Kim
3.3 String.prototype.indexOf(searchString: string, fromIndex=0): number ES1 인수로 전달한 문자 또는 문자열을 대상 문자열에서 검색하여 처음 발견된 곳의 index를 반환한다.
발견하지 못한 경우 -1을 반환한다.
// str.indexOf(searchString[, fromIndex])
// searchString : 검색할 문자 또는 문자열
// fromIndex : 검색 시작 index (생략할 경우, 0)
conststr='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을 반환한다.
2번째 인수(fromIndex)가 전달되면 검색 시작 위치를 fromIndex으로 이동하여 역방향으로 검색을 시작한다.
이때 검색 범위는 0 ~ fromIndex이며 반환값은 indexOf 메소드와 동일하게 발견된 곳의 index이다.
conststr='Hello World';
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
3.5 String.prototype.replace(searchValue: string | RegExp, replaceValue: string | replacer: (substring: string, …args: any[]) => string): string): string ES3 첫번째 인수로 전달한 문자열 또는 정규표현식을 대상 문자열에서 검색하여 두번째 인수로 전달한 문자열로 대체한다.
원본 문자열은 변경되지 않고 결과가 반영된 새로운 문자열을 반환한다.
conststr='Hello world world';
// 첫번째로 검색된 문자열만 대체하여 새로운 문자열을 반환한다.
console.log(str.replace('world', 'Lee')); // Hello Lee world
// 특수한 교체 패턴을 사용할 수 있다. ($& => 검색된 문자열)
console.log(str.replace('world', '<strong>$&</strong>')); // Hello <strong>world</strong> world
//정규표현식
console.log(str.replace(/world/gi, 'Lee')); // Hello Lee Lee
// 두번째 인수로 치환 함수를 전달할 수 있다.
// camelCase => snake_case
constcamelCase='helloWorld';
// /.[A-Z]/g => 1문자와 대문자의 조합을 문자열 전체에서 검색한다.
console.log(camelCase.replace(/.[A-Z]/g, function (match) {
console.log(snakeCase.replace(/_./g, function (match) {
// match : _w => match[1] : w
returnmatch[1].toUpperCase();
})); // helloWorld
3.6 String.prototype.split(separator: string | RegExp, limit?: number): string[] ES3 첫번째 인수로 전달한 문자열 또는 정규표현식을 대상 문자열에서 검색하여 문자열을 구분한 후 분리된 각 문자열로 이루어진 배열을 반환한다. 원본 문자열은 변경되지 않는다.
console.log('abc'.repeat(-1)); // RangeError: Invalid count value
3.13 String.prototype.includes(searchString: string, position?: number): boolean ES6 인수로 전달한 문자열이 포함되어 있는지를 검사하고 결과를 불리언 값으로 반환한다.
두번째 인수는 옵션으로 검색할 위치를 나타내는 정수이다.
conststr='hello world';
console.log(str.includes('hello')); // true
console.log(str.includes(' ')); // true
console.log(str.includes('wo')); // true
console.log(str.includes('wow')); // false
console.log(str.includes('')); // true
console.log(str.includes()); // false
// String.prototype.indexOf 메소드로 대체할 수 있다.
console.log(str.indexOf('hello')); // 0
정리
str.concat(str2 [,str3]) : str 문자열과 str2 연결한 문자열 반환 str+str2 : str 문자열과 str2 연결한 문자열 반환 (성능 유리) str.charAt(index) : 해당 index의 문자 반환 str[index] : 해당 index의 문자 반환 str.indexOf(search) : str 에서 search 를 찾아 index 반환 str.lastIndexOf(search [,index]) : str의 index 위치에서 역방향으로 search 를 찾아 index 반환 str.replace(search, str2) : str 에서 search 를 찾아 str2 로 대체하여 문자열 반환 str.split(sep[, limit]) : str 에서 sep 를 구분자로 사용하며 limit 갯수만큼 배열로 반환 str.substring(start, end) : str을 start 에서 end-1 까지 인덱스의 문자열 반환 str.slice(start, end) : str을 substring 과 같으며, 음수에 대해서 뒤에서부터 문자열 반환 str.toLowerCase() : str 을 소문자로 변경 str.toUpperCase() : str 을 대문자로 변경 str.trim() : str 의 공백 제거 str.repeat(n) : str을 n번 반복 연결한 문자열 반환 str.includes(search) : str 에 search 가 포함되면 true