문자열의 특징

  • 문자열 : string
  • 문자 하나 : character (줄여서 char)

1. index로 접근 가능하지만, 수정할 수는 없다.(read-only)

const str = 'abcde';
console.log(str[3]); // 'd'
const str = 'abcde';
str[3] = D;
console.log(str[3]); // 'd'

bracket notation

: 대괄호[ ]를 이용해 문자열의 문자, 배열의 요소, 객체의 속성을 조회하는 방식

2. + 연산자를 쓸 수 있다.

문자열 + 문자열

const str1 = 'abc';
const str2 = 'def';
console.log(str1 + str2); // 'abcdef'

문자열 + 다른 type
: string type과 다른 type 사이에 + 연산자를 사용하면, 모두 string 타입으로 변환된다.

const str = '123';
console.log(str + 456);  // '123456'       : string + number
console.log(str + true); // '123true'      : string + boolean
console.log(str + [4, 5, 6]) // '1234,5,6' : string + array

문자열의 프로퍼티

.length

str.length : 문자열의 길이를 반환한다.

const str = 'abcde';
console.log(str.length) // 5

문자열 메소드

.indexOf()

str.indexOf(searchValue) : 문자열을 찾아서 처음으로 일치하는 index를 반환하는 메소드

'banana'.indexOf('a'); // 1
'banana'.indexOf('n'); // 2

str.lastIndexOf(searchValue) : 문자열을 뒤에서부터 찾아서 처음으로 일치하는 index를 반환하는 메소드

'banana'.lastIndexOf('a'); // 5
  • 일치하는 문자열이 없으면 -1을 반환한다.
'banana'.indexOf('z'); // -1
'banana'.lastIndexOf('z'); // -1

.includes()

str.includes(searchValue) : 찾는 문자열이 포함되어 있으면 true, 포함되어있지 않으면 false를 반환하는 메소드

'banana'.includes('b'); // true
'banana'.includes('z'); // false

.concat()

str1.concat(str2, str3 ...) : 매개변수로 전달된 모든 문자열을 호출 문자열에 붙여서, 새로운 문자열을 반환하는 메소드

const str1 = 'Hello';
const str2 = 'World';
str1.concat(', ', str2, '!'); // 'Hello, World!'

.join()

arr.join(separator) : 배열 안의 요소를 연결해 문자열로 반환하는 배열 메소드

const langs = ['HTML', 'CSS', 'JavaScript'];
langs.join();    // 'HTML,CSS,JavaScript' 괄호가 비어있으면 쉼표(,)로 연결
langs.join('-'); // 'HTML-CSS-JavaScript' 괄호 안의 문자로 연결

.split()

str.split(sepeartor) : 특정 문자를 기준으로 문자열을 분리하고, 새로운 배열을 만들어 반환하는 메소드

const str = `I'd like to eat some bananas.`
str.split(' ');
// (6) ["I'd", 'like', 'to', 'eat', 'some', 'bananas.']
  • CSV(파일형식)를 다룰 때 사용하면 편하다.

    CSV (Comma-Separated Values)

    : 표 형태의 데이터를 쉼표(,)로 구분해 텍스트 데이터로 저장한 파일 형식
    줄바꿈 문자 \n 와 쉼표 ,를 기준으로 문자열을 분리해 배열로 반환하게 할 수 있다.


.substring()

str.substring(start, end) : 시작하고 끝나는 index를 입력하면 그 사이의 문자열을 반환하는 메소드

const str = 'abcde';
str.substring(0,2); // index 0~1을 반환 -> 'ab'
str.substring(0,5); // index 0~4를 반환 -> 'abcde'

.slice()

str.slice(start, end) : 문자열의 일부를 추출하여 새로운 문자열을 반환하는 메소드

const str = 'abcde';
str.slice(0,2); // index 0~1을 반환 -> 'ab'
str.slice(0,5); // index 0~5를 반환 -> 'abcde'
  • negative index(-)를 사용할 수 있다.
const str = 'abcde';
str.slice(0,-1); // index 0~-2를 반환 -> 'abcd'
str.slice(0,-2); // index 0~-3을 반환 -> 'abc'
  • 배열에도 사용할 수 있다. arr.slice()

.replace()

str.replace(searchValue, newValue) : 특정 문자열을 찾아 다른 문자열로 치환하여 새로운 문자열을 반환하는 메소드

  • 첫번째로 찾은 문자열만 치환한다.
const str = 'abcdec';
str.replace('c', 'C'); // 'abCdec'

➡️ 만약에 문자열 내에서 찾아낸 모든 문자열에 대해서 치환하고 싶다면 정규표현식을 사용해야 한다.


.trim()

str.trim() : 문자열 양 끝의 공백을 제거하는 메소드

  • 공백이란 모든 공백문자(space, tab, NBSP 등)와 모든 개행문자(LF, CR 등)를 의미한다.
const greeting = '   Hello world!   ';
greeting.trim(); // 'Hello world!'

NBSP (Non-breaking space)

  : 웹페이지에서 공백을 표시하기 위해 사용하는 특수문자

  • 웹 브라우저나 스크립트 엔진은 여러 개의 공백이 있는 경우 1개의 공백만 표시하기 때문에, 웹페이지에서 여러 개의 공백을 넣어야 한다면  를 반복 입력한다.

CR (Carriage Return)

\r : 현재 줄에서 커서를 줄의 맨 앞으로 옮기는 동작

LF (Line Feed)

\n : 현재 커서의 위치에서 한 줄 아래로 이동하는 동작 (커서의 위치 변화 없이)


.repeat()

str.repeat(count) : 문자열을 주어진 횟수만큼 반복해 붙여 새로운 문자열을 반환하는 메소드

const str = 'abcde';
str.repeat(3); // 'abcdeabcdeabcde'

.toLowerCase() / .toUpperCase()

str.toLowerCase() : 대문자를 소문자로 변환하는 메소드

const str = 'ABCDE';
str.toLowerCase(); // 'abcde'

str.toUpperCase() : 소문자를 대문자로 변환하는 메소드

const str = 'abcde';
str.toUpperCase(); // 'ABCDE'

문자열로 변환하는 메소드

String()

String(value) : 값(value)을 문자열로 변환해주는 메소드

let num = 12345;
String(num) // '12345'

.toString()

.toString() : type을 문자열로 변환해주는 메소드

let num = 12345;
num.toString(); // '12345'

.toString(radix) : 숫자나 Bigints의 경우, 매개변수로 radix(기수)를 받아 10진수를 다른 진수로 변환할 수 있다.

  • radix(기수) : 2 ~ 36 진법
let num = 10;
num.toString(2); // '1010' : 10을 2진수로 변환

String().toString()의 차이

  • String() : 어떤 type이든 값을 문자열로 변환한다.
String(null);      // 'null'
String(undefined); // 'undefined'
  • .toString() : null(빈 값)과 undefined(할당되지 않은 값)은 type 변환 시 에러가 발생한다.
null.toString();      // ❗️Uncaught TypeError: Cannot read properties of null (reading 'toString')
undefined.toString(); // ❗️Uncaught TypeError: Cannot read properties of undefined (reading 'toString')

mutable? immutable?

immutable : 원본이 변하지 않는다.
mutable : 원본이 변한다.

  • 모든 string 메소드는 immutable이다.
  • array 메소드는 immutable/mutable의 여부를 잘 기억해야 한다.

❔ 학습 후 궁금한 점

  • substring()과 slice()에 대해 더 자세히 비교해보기
  • slice()의 negative index의 개념에 대해 제대로 이해하지 못했다..🥲
  • 정규표현식 사용법
profile
개발 공부 기록 블로그

0개의 댓글