TIL 문자열

Samuel .J·2022년 1월 22일
0
post-thumbnail

str.indexOf(searchValue)

  • indexOf() 메서드는 호출한 String 객체에서 주어진 값과 일치하는 첫 번째 인덱스를 반환합니다. 일치하는 값이 없으면 -1을 반환합니다.
  • lastIndexOf() 메서드는 주어진 값과 일치하는 부분을 역순으로 탐색해 최초로 마주치는 인덱스를 반환한다.
'hello word'.indexOf('hello');  // 0
'hello word'.indexOf('word');  // 6
'hello word'.indexOf('good');  // -1

// lastIndexOf() 와 indexOf() 차이점 비교
'hello word'.indexOf('l');  // 2
'hello word'.lastIndexOf('l'); // 3

str[index]

str[index] 사용방법

let str = 'Tokyo'
console.log(str[0]) // 'T'
console.log(str[2]) // 'k'
console.log(str[4]) // 'o'

Concatenating strings(문자열 나열)

  • +연산자를 쓸 수 있다.
  • string 타입과 다른 타입 사이에 + 연산자를 쓰면, string 형식으로 변환
let str1 = 'hello';
let str2 = 'word';
let str3 = '3';
console.log(str1 + str2); // 'helloword'
console.log(str1 + ' ' + str2); // 'hello word'
console.log(str3 + 7) // '37'

str.length

  • str.length를 사용하면 문자열의 전체 길이를 반환 (주의 : str의 길이 를 나타내는 것이지 인덱스를 나타내는 것 은 아니다!)
let str = 'hello';
console.log(str.length); // str문자열의 길이는 5가 출력 하지만
                         // 인덱스 값은 4 차이점 알아둬야함!

str.split

split() 메서드는 String 객체를 지정한 구분자를 이용하여 여러 개의 문자열로 나눕니다.

let str = 'My name is TaeSung';
console.log(str.split(' ')) //  띄어쓰기 기준 ['My', 'name', 'is', 'TaeSung']
console.log(str.split('')) //  인덱스 마다 기준  ['M', 'y', ' ', 'n', 'a', 'm', 'e', ' ', ..., 'g']

str.toLowerCase() , str.toUpperCase()

  • 문자열을 대문자 또는 소문자로 전부 변환시켜줌
let str = 'Hello'
console.log(str.toLowerCase()); // 출력값은 hello 즉 소문자로 변경
console.log(str.toUpperCase()); // 출력값은 HELLO 즉 대문자로 변경

str.slice, str.substring

  • slice(시작index, 끝index) 메소드는 문자열의 일부를 추출하면서 새로운 문자열을 반환합니다. 끝index 전까지 반환한다.
let str = "안녕하세요?"
str.slice(1) // '녕하세요?'

let first_char = str.slice(0, 1);
console.log(first_char) // 안
let second_char = str.slice(1, 2);
console.log(second_char) // 녕
let last_char = str.slice(str.length-1, str.length);
console.log(last_char) // ?
  • str.substring도 마찬가지로 str.slice 비슷한 기능을 가지고 있다. 차이점이 궁금하다면 아래 링클를 통해 확인해 보자!
    str.slice, str.substring 차이점!
profile
기록하는 코린이의 블로그🥸

0개의 댓글