본문 바로가기

Web/Javascript

[JAVASCRIPT] STRING

STRING

  • 자바스크립트의 원시타입인 string 이 가지는 메소드를 기술한다.
  • 메소드는 string wrapper 객체가 가지고 있다.

length

  • String 래퍼 객체는 length 프로퍼티를 갖는다.
  • String 래퍼 객체는 유사 배열 객체이다.
"Hello".length;    // -> 5

String.prototype.indexof

  • 인수로 전달받은 문자열을 검색하여 첫번째 인덱스를 반환.
  • 값이 없는 경우 -1 반환
const str = "Hello World";

str.indexOf("l");    // 2
str.indexOf("or");   // 7
str.indexOf("x");    // -1

// str 인덱스 3부터 "l" 을 검색하여 첫 번째 인덱스를 반환.
str.indexOf("l", 3);     // 3
// 특정 문자열의 존재 여부
if(str.indexOf("Hello") !== -1) {}

String.prototype.search

  • 정규표현식 과 일치하는 문자열을 검색하여 반환
  • 값이 없는 경우 -1 반환
const str = "Hello World";

str.search(/o/);    // 4;
str.search(/x/);    // -1;

String.prototype.includes

  • ES6
  • 인수로 전달받은 문자열이 포함되어있는지 확인하여 boolean 리턴
const str = "Hello World";

str.includes("Hello");    // true
str.includes("x");    // false

String.prototype.startsWith

  • 인수로 전달받은 문자열로 시작하는지 확인하여 boolean 리턴
  • 두번째 인자 (숫자) 인덱스 부터 시작하여 첫번째 인자 로 시작하는지 확인한다.
const str = "Hello World";

str.startWith("He");    // true
str.startWith("Hello");    // true
str.startWith("x");    // false

str.startWith(" ", 5);    // true

String.prototype.endsWith

  • 인수로 전달받은 문자열로 끝나는지 확인하여 boolean 리턴
  • 두번째 인자 자릿수까지 문자열이 첫번째 인자로 끝나는지 확인한다.
const str = "Hello World";

str.endsWith("d");    // true
str.endsWith("World");    // true
str.endsWith("x");    // false

str.endsWith("lo", 5);    // true

String.prototype.charAt

  • 문자열 에서 인수로 전달받은 인덱스에 위치한 문자를 반환한다.
  • 문자열 범위를 벗어난 경우 빈 문자열을 반환한다.
const str = "Hello World";

console.log(str.charAt(1));    // "H"
console.log(str.charAt(2));    // "e"
console.log(str.charAt(3));    // "l"

console.log(str.charAt(99));    // ""

String.prototype.substring

  • 첫 번째 인수로 전달받은 인덱스에 위치하는 문자부터 두 번째 인수로 전달받은 인덱스 위치하는 문자 전 까지 부분의 문자열을 리턴한다.
  • 첫 번째 인수가 두 번째 인수보다 큰경우 두인수는 교체된다.
  • 인수가 0 또는 NaN 경우 0 으로 취급된다.
  • 인수가 길이를 초과하는경우 문자열 길이로 취급된다.
const str = "Hello World";

str.substring(1, 5);    // "ello"
str.substring(2);    // "llo World"

str.substring(5, 1);    // "ello"

str.substring(-4);    // "Hello World"

str.substring(2, 100);    // "llo World"
str.substring(100);    // ""
const str = "Hello World";

str.substring(0, str.indexOf(" "));    // "Hello"
str.substring(str.indexOf(" ") + 1, str.length );    // "World"

String.prototype.slice

  • substring 과 동일하게 동작한다.
  • 단 slice 메서드에서는 음수를 인수로 전달가능하다.
  • 음수를 인수로 전달하면 문자열의 뒤부터 시작하여 문자열을 잘라내 반환한다.
const str = "Hello World";

str.slice(0, 5);    // "Hello"
str.slice(2);    // "llo World"

str.substring(-5);    // "Hello World"
str.slice(-5);    // "World"

String.prototype.toUpperCase, String.prototype.toLowerCase

  • 문자열을 대문자 | 소문자 로 변경한 문자열을 반환한다.
const str = "Hello World";

str.toUpperCase();    // "HELLO WORLD"
str.toLowerCase();    // "hello world"

String.prototype.trim

  • 앞뒤 공백을 제거한다.
  • 추가적으로 trimStart , trimEnd 메소드 가 존재한다
const str = "     hi    ";
str.trim();    // "hi";

String.prototype.repeat

  • ES6
  • 인수로 전달받은 정수 만큼 반복해 새로운 문자열을 리턴한다.
  • 음수의 경우 에러를 발생시킨다.
  • 인자의 기본값은 0
const str = "Hello";

str.repeat(-1);    // error
str.repeat();    // ""
str.repeat(0);    // ""
str.repeat(1);    // "Hello"
str.repeat(2);    // "HelloHello"
str.repeat(2.5);    // "HelloHello"

String.prototype.replace

  • 첫 번째 인수로 전달 받은 (문자열 | 정규표현식) 을 검색하여 두 번째 인수로 전달한 문자열로 치환한다.
  • 정규 표현식으로 전부 변경 가능하다.
  • 신규 메소드로 replaceAll 존재한다.
const str = "Hello World";

str.replace("World", "Sky");    // "Hello Sky"
str.replace("l", "e");    // "Heelo World"

str.replace(/l/gi, "x");    // Hexxo Worxd"
// 카멜케이스 -> 스네이크케이스
function camelToSnake(camelCase){
	return camelCase.replace(/.[A-Z]/g, match => {
		return match[0] + "_" + match[1].toLowerCase();
	});
}

// 스네이크케이스 -> 카멜케이스
function snakeToCamel(snakeCase){
	return snakeCase.replace(/_[a-z]/g, match => {
		return match[1].toUpperCase;
	});
}

String.prototype.split

  • 첫 번째 인수로 전달한 (문자열 | 정규표현식) 을 검색하여 분리된 배열로 반환한다.
const str = "have a good day";

str.split(" ");    // ["have", "a", "good", "day"]
str.split(/\\\\s/);    // ["have", "a", "good", "day"]
str.split("");    // ["h", "a", "v", ... "y"]
str.split();    // ["have a good day"]
// 문자 뒤집기
const str = "have a good day";

str.split("").reverse().join("");
// "yad doog a evah"

String.prototype.padStart

  • ES8
  • 메서드는 현재 문자열의 시작을 다른 문자열로 채워, 주어진 길이를 만족하는 새로운 문자열을 반환한다.
const str = '5';

console.log(str.padStart(2, '0'));    // "05"

String.prototype.padEnd

  • ES8
  • 메서드는 현재 문자열의 시작을 다른 문자열로 채워, 주어진 길이를 만족하는 새로운 문자열을 반환한다.
  • 채워넣기는 대상 문자열의 끝(우측)부터 적용된다.
const str = '1';

console.log(str.padEnd(5, "0"));    // "10000"

Reference

  • 모던자바스크립트 Deep Dive - 이웅모

There might be incorrect information or outdated content.

'Web > Javascript' 카테고리의 다른 글

[JAVASCRIPT] DOM - 노드 조작  (0) 2023.08.04
[JAVASCRIPT] DOM - 노드 탐색  (0) 2023.08.04
[JAVASCRIPT] DOM - 노드 취득 (HTMLCollection)  (0) 2023.08.04
[JAVASCRIPT] Full Screen  (0) 2023.07.29
[JAVASCRIPT] ARRAY  (0) 2023.07.28