logo
Search검색어를 포함하는 게시물들이 최신순으로 표시됩니다.
    Table of Contents
    [JS CS] 문자열

    이미지 보기

    [JS CS] 문자열

    • 22.04.26 작성

    • 읽는 데 2

    TOC

    문자열(String)

    메서드 1 : includes

    • string.includes(value)
    • 문자열에 value가 존재하는지 판별 후 참 또는 거짓 반환
    const str = 'a santa at nasa'
    
    str.includes('santa') // true
    str.includes('asan')  // false
    

    메서드 2 : split

    • string.split(value)

    value : 나누는 기준

    • 없다 : string을 배열에 담아 반환
    • 빈 문자열 : 한 문자씩 나눈 배열 반환
    • 기타 문자열 : 해당 문자열로 나눈 배열 반환
    const str = 'a cup'
    
    str.split()     // ['a cup']
    str.split('')   // ['a', ' ', 'c', 'u', 'p']
    str.split(' ')  // ['a', 'cup']
    

    메서드 3 : replace

    • string.replace(from, to)

    • 문자열에 from 값이 존재할 경우, 1개만 to 값으로 교체하여 반환

    • string.replaceAll(from, to)

    • 문자열 내의 모든 from을 to로 교체해 반환

    const str = 'a b c d'
    
    str.replace(' ', '-')     // a-b c d
    str.replaceAll(' ', '-')  // a-b-c-d
    

    메서드 4 : trim

    • 문자열의 앞뒤의 공백문자 제거(' ', \t, \n)
    • str.trim() : 시작과 끝 모두 제거
    • str.trimStart() : 시작의 공백 제거
    • str.trimEnd() : 끝의 공백 제거
    const str = '     hello     '
    
    str.trim()         // 'hello'
    str.trimStart()    // 'hello     '
    str.trimEnd()      // '     hello'
    
    profile

    FE Developer 박승훈

    노력하는 자는 즐기는 자를 이길 수 없다