JS 데이터 #문자 (string)

달다로·2024년 6월 9일

JS

목록 보기
17/26
post-thumbnail

📌 String (문자)

문자열의 생성자

다른 글에서 이어집니다!


String.prototype.indexOf()

호출한 string 객체에서 주어진 값과 일치하는 첫번째 인덱스를 반환하고, 일치하는 값이 없으면 -1을 반환한다.

  • prototype : 메모리에 딱 한번 지정이 됨
  • new String = Sting → 하나의 새로운 객체 생성

    dog 이 첫번째로 위치한 곳 까지의 문자갯수 (I 부터 0으로 카운트됨)
const result = 'Hello world!.indexOf('world')
console.log(result) // 결과 : 6

const result = 'Hello world!.indexOf('daldaro')
console.log(result) // 결과 : -1, 결과 없음

1) 매개변수

  • searchValue
    찾으려는 문자열
  • fromIndex

2) 반환 값

searchValue 의 첫번째 인덱스, 찾을 수 없으면 -1

const str = '0123'

console.log(str) //0123
console.log(str.length) //4, 글자가 몇개인지
console.log(0123.length) //4, str 을 지정하지 않고 바로 적어도 가능
console.log(str.indexOf('daldaro') !== -1) //false, boolean 데이터로 확인하는 방법

String.prototype.slice()

문자열의 일부를 추출하면서 새로운 문자열을 반환함

1) 매개변수

  • beginIndex
    0부터 시작하는 인덱스
  • endIndex
    0부터 시작하는 추출 종료점 인덱스이며 그 직전까지 추출된다.
    (0, 3)이면 0~2번째까지 표시됨

2) 반환 값

searchValue 의 첫번째 인덱스, 찾을 수 없으면 -1

const str = 'Hello world!.indexOf('world')

console.log(str.slice(0, 3)) //Hel, 0 에서 시작해서 3번째 위치까지 표시함
console.log(str.slice(6, 11)) //world
console.log(str.replace'world', 'daldaro')) //Hello daldaro!, world부분 대신 daldaro를 넣음

String.prototype.match()

문자열에서 특정 패턴 을 찾는데 사용되는 함수이다.

1) 문자 찾기

local text = "나는 사과를 좋아해"
local result = string.match(text, "사과")
print(result) // 사과

2) 숫자 찾기

  • %d+ : 숫자를 의미하는 패턴
local text = "전화번호는 123-456-7890"
local result = string.match(text, "%d+")
print(result) // 123

3) 특정 패턴의 문자열 찾기

  • %a+ : 알파벳 문자
  • @ : @ 기호
  • %. : . 기호

예제 1번

local text = "이메일은 example@domain.com 이야"
local result = string.match(text, "%a+@%a+%.%a+")
print(result) // example@domain.com

예제 2번

const str = 'example@domain.com'

console.log(str.match(/.+(?=@)/)[0]) //정규표현식, example

3) 특정 위치에서 찾기

local text = "오늘은 일요일이에요"
local result = string.match(text, "일요일", 4) // 4번째 위치부터 일요일이라는 단어를 찾아
print(result) // 일요일

String.prototype.trim()

자동으로 공백 제거

const str = '            Hello world '
console.log(str.trim())
profile
나이들어서 공부함

0개의 댓글