String 32

String 메서드

String.prototype.indexOf

index 값을 반환한다.

const str = 'hello world';
str.indexOf('e'); // 1
str.indexOf('x'); // -1

// 두번째 인수: 검색을 시작할 인덱스
str.indexOf('l',5); // 9

indexOf 메서드는 대상 문자열에 특정 문자열이 존재하는지 확인할 때 유용하다.

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

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

정규표현식을 인수로 받는다.
index 값을 반환한다.

const str = 'hello world';
str.search(/o/); // 4
str.search(/x/); // -1

String.prototype.includes

boolean 값을 반환한다.

const str = 'hello world';
str.includes('o'); // true
str.includes('x'); // false

// 두번째 인수: 검색을 시작할 인덱스
str.includes('h', 3); // false

String.prototype.startsWith

대상 문자열이 인수로 전달받은 문자열로 시작하는지 확인하여 결과를 true false로 반환한다.

const str = 'hello world';
str.startsWith('he'); // true

String.prototype.endsWith

대상 문자열이 인수로 전달받은 문자열로 끝나는지 확인하여 결과를 true false로 반환한다.

const str = 'hello world';
str.endsWith('ld'); // true

String.prototype.charAt

대상 문자열에서 인수로 전달받은 인덱승 위치한 문자를 검색하여 반환한다.
비슷한 문자열 메서드로 String.prototype.charCodeAt 과 String.prototype.codePointAt 이 있다.

const str = 'hello';
for(let i=0; i<str.length; i++){
    console.log(str.charAt(i)); // h e l l o
}

String.prototype.substring

첫 번째 인수로 전달받은 인덱스에 위치하는 문자부터 두 번째 인수로 전달받은 인덱스에 위치하는 문자의 바로 이전 문자까지의 부분 문자열을 반환한다.

const str = 'hello world';
str.substring(1,4); // ell
str.substring(2); // llo world
  • 첫 번째 인수 > 두 번째 인수인 경우 두 인수는 교환된다.
  • 인수 < 0 또는 NaN인경우 0으로 취급된다.
  • 인수 > 문자열의 길이인 경우 인수는 문자열의 길이로 취급된다.
    String.prototype.indexOf 메서드와 함께 사용하면 특정 문자열을 기준으로 앞 뒤에 위치한 부분 문자열을 취득할 수 있다.
const str = 'hello world';
str.substring(0, str.indexOf(' ')); // ' ' 기준 앞 문자열 : 'hello'
str.substring(str.indexof(' ')+1, str.length); // ' ' 기준 뒷 문자열 : 'world'

String.prototype.slice

slice 메서드는 substring 메서드와 동일하게 동작한다.
단, slice 메서드에는 음수인 인수를 전달할 수 있다.
음수인 인수를 전달하면 대상 문자열의 가장 뒤에서부터 시작하여 문자열을 잘라내어 반환한다.

const str = 'hello world';
str.slice(-3); // 'rld'

String.prototype.toUpperCase

대상 문자열을 모두 대문자로 변경한 문자열을 반환한다.

const str = 'Hello World';
str.toUpperCase(); // 'HELLO WORLD'

String.prototype.toLowerCase

대상 문자열을 모두 소문자로 변경한 문자열을 반환한다.

const str = 'Hello World';
str.toLowerCase(); // 'hello world'

String.prototype.trim

trim 메서드는 대상 문자열 앞뒤에 공백 문자가 있을 경우 이를 제거한 문자열을 반환한다.

const str = '   foo   ';
str.trim(); // 'foo'

String.prototype.repeat

대상문자열을 인수로 전달받은 정수만큼 반복해 새로운 문자열을 반환한다.
인수 기본값은 0이고, 0을 전달받으면 빈 문자열을 반환한다.

const str = 'abc';
str.repeat(2); // 'abcabc'

String.prototype.replace

대상 문자열에서 첫 번째 인수로 전달받은 문자열 또는 정규표현식을 검색하여 두 번째 인수로 전달한 문자열로 치환한 문자열을 반환한다.

const str = 'hello world';
str.replace('he', 'lee'); // 'leello world'

String.prototype.split

split 메서드는 대상 문자열에서 첫 번째 인수로 전달한 문자열 또는 정규 표현식을 검색하여 문자열을 구분한 후 분리된 각 문자열로 이루어진 배열을 반환한다.
인수로 빈 문자열을 전달하면 각 문자를 모두 분리하고,
인수를 생략하면 대상 문자열 전체를 단일 요소로 하는 배열을 반환한다.

function reverseString(str){
    return str.split('').reverse().join('');
}
reverseString('hi'); // ih