[Javascript]-string-메소드

오다경·2022년 11월 23일
0

javascript basic

목록 보기
5/12

string의 다양한 메소드

.split()

String 객체를 지정한 구분자를 이용하여 여러 개의 문자열로 나눈다.

const str = 'a,b,c,d,e,f,g'
str.split(',') // ['a', 'b', 'c', 'd', 'e', 'f', 'g']
str.split(',',3) // ['a','b','c']
'Why would you doubt my word?'.split(''); // ['W', 'h', 'y', ' ', 'w', 'o', 'u', 'l', 'd', ' ', 'y', 'o', 'u', ' ', 'd', 'o', 'u', 'b', 't', ' ', 'm', 'y', ' ', 'w', 'o', 'r', 'd', '?']
'Why would you doubt my word?'.split(' ') // ['Why', 'would', 'you', 'doubt', 'my', 'word?']
'Why would you doubt my word?'.split() // ['Why would you doubt my word?']

.repeat()

문자열을 주어진 횟수만큼 반복해 붙인 새로운 문자열을 반환한다.

console.log("안녕".repeat(3)) //안녕안녕안녕

.includes()

하나의 문자열이 다른 문자열에 포함되어 있는지를 판별하고, 결과를 true 또는 false 로 반환한다

console.log("hi dakyung".includes("da")) // true

.indexOf

호출한 String 객체에서 주어진 값과 일치하는 첫 번째 인덱스를 반환한다.
이 메소드는 대소문자를 구분한다.
일치하는 값이 없으면 -1을 반환한다.

console.log('Are you sure?'.indexOf('sure')) //8
console.log('Are you sure?'.indexOf('suee')) //-1

.startsWith()

어떤 문자열이 특정 문자로 시작하는지 확인하여 결과를 true 혹은 false로 반환한다.
단, searchString을 탐색하여 string의 시작할 위치를 지정하면 true로 반환이 가능하다.

console.log('what are you doing?'.startsWith('what')) //true
console.log('what are you doing?'.startsWith('are')) //false
console.log('what are you doing?'.startsWith('are',5)) // true

.endsWith()

메서드를 사용하여 어떤 문자열에서 특정 문자열로 끝나는지를 확인할 수 있으며, 그 결과를 true 혹은 false로 반환한다.
단 lengths는 옵션으로, 문자열의 길이값은 문자열 전체 길이 안에서만 존재하여야 한다.

console.log('what are you doing?'.endsWith('ing?')) // true
console.log('what are you doing?'.endsWith('what')) // false
console.log('what are you doing?'.endsWith('ing?',25)) // true

.slice()*

문자열의 일부를 추출하면서 새로운 문자열을 반환한다.
slice()는 endIndex를 포함하지 않고 추출한다.
eg) str.slice(1, 4)는 두 번째 문자부터 네 번째 문자까지 추출한다.
eg) str.slice(2, -1)는 세 번째 문자부터 문자열의 마지막에서 두 번째 문자까지 추출한다.

console.log('Hello my name is dakyung'.slice(1)) // 'ello my name is dakyung'
console.log('Hello my name is dakyung'.slice(1,4) // 'ell'
consoel.log('Hello my name is dakyung'.slice(2,-1)
) // 'llo my name is dakyun'

.trim()*

문자열 양 끝의 공백을 제거한다. 공백이란 모든 공백문자(space, tab, NBSP 등)와 모든 개행문자(LF, CR 등)를 의미한다.

const animals = 'dog   '
console.log(animals.trim()) // 'dog'
profile
개발자 꿈나무🌳

0개의 댓글