기록

기본 함수 정리 (String)

안녕하세요 청이 입니다.

JS에서 기본적으로 제공하는 유용한 함수에 대하여 정리하도록 하겠습니다.


JS Stirng의 기본 길이 : UTF-16 ( 약 216 승, 65536개 )

문자열 반복

수동 반복
String.[Symbol.iterator]()

const str = 'The quick red fox jumped over the lazy dog\'s back.';

const iterator = str[Symbol.iterator]();

let theChar = iterator.next(); // T .. h.. e .. next() 호출 마다

문자열 찾기 (문자 반환)
String.at() : at(number)
정수 or 음수의 숫자를 받아 String에서 값을 찾아 반환 합니다.
정수 : String의 앞에서 부터 숫자 만큼 계산된 값
음수 : Stirng의 뒤에서 부터 숫자 만큼 계산된 값

지정된 범위를 넘어서면, undefined 반환

const sentence = 'The quick brown fox jumps over the lazy dog.';

let index = 5;
console.log(`${sentence.at(index)}`);
// "u"

index = -4;
console.log(`Using an index of ${index} the character returned is ${sentence.at(index)}`);
// "d"

String.charAt() : charAt(number)
정수만 받아 값을 찾으며, 범위를 벚어 날 경우 빈값을 반환 ''
정수를 제공하지 않으면 기본값은 0 이다.

String.charCodeAt() : charCodeAt(number)
정수만 받아 값을 찾으며, 범위를 벚어 날 경우 NaN 반환
정수를 제공하지 않으면 기본값은 0 이다.

문자열 연결
Stirng.concat() : concat(str1, str2, /* …, */ strN)
주어진 만큼의 값을 모두 연결하여 하나의 문자열로 반환
만약, 문자열이 아닌 값이 주어 졌으면, 문자열로 강제 변환후 연결

const str1 = 'Hello';
const str2 = 'World';

console.log(str1.concat(' ', str2));
// Expected output: "Hello World"

console.log(str2.concat(', ', str1));
// Expected output: "World, Hello"

String.search(regexp)
반환값 : 일치하는 문자열의 위치 or -1

const str = "hey JudE";
const re = /[A-Z]/;
const reDot = /[.]/;
console.log(str.search(re)); // returns 4, which is the index of the first capital letter "J"
console.log(str.search(reDot)); // returns -1 cannot find '.' dot punctuation

문자열 검사

문자열의 시작이 지정된 문자열인지 확인
Stirng.startsWith() : endsWith(searchString, position)
searchString : 찾고자하는 문자열(정규식 불가)
옵션, position : 검색을 시작하고자 하는 위치 ( 기본 값 : 0 )
반환값 : Boolean

const str1 = 'Saturday night plans';

console.log(str1.startsWith('Sat'));
// Expected output: true

console.log(str1.startsWith('Sat', 3));
// Expected output: false

문자열의 마지막이 지정된 문자열인지 확인
Stirng.endsWith() : endsWith(searchString, endPosition)
searchString : 찾고자하는 문자열(정규식 불가)
옵션, endPosition : 검색을 시작하고자 하는 위치 ( 기본 값, searchStirng.length)
반환값 : Boolean

const str1 = 'Cats are the best!';

console.log(str1.endsWith('best!'));
// Expected output: true

console.log(str1.endsWith('best', 17));
// Expected output: true

const str2 = 'Is this a question?';

console.log(str2.endsWith('question'));
// Expected output: false

문자열내 지정된 문자열이 있는지 확인
Stirng.includes() : includes(searchString, position)
searchString : 찾고자하는 문자열(정규식 불가), stirng으로 강제 변환, 기본값 : "undefined"
옵션, position : 검색을 시작하고자 하는 위치 ( 기본 값 : 0 )
반환값 : Boolean

const sentence = 'The quick brown fox jumps over the lazy dog.';

const word = 'fox';

console.log(`${sentence.includes(word) ? 'is' : 'is not'}`);
// "is"

문자열내 지정된 문자열의 위치 확인
searchString : 찾고자하는 문자열(정규식 가능), stirng으로 강제 변환, 기본값 : "undefined"
옵션, position : 검색을 시작하고자 하는 위치 ( 기본 값 : 0 )
또한, 지정된 position와 같거나 큰 위치 에서만 값을 찾는다.

반환값 : Index 값 ( number) 없는 경우 -1
특징 : 만약 값이 2개 이상 있을 경우, 첫번째 값의 위치를 제공하고 종료 한다.
대소문자 구분

"Blue Whale".indexOf("Blue"); // returns  0
"Blue Whale".indexOf("Blute"); // returns -1
"Blue Whale".indexOf("Whale", 0); // returns  5
"Blue Whale".indexOf("Whale", 5); // returns  5
"Blue Whale".indexOf("Whale", 7); // returns -1
"Blue Whale".indexOf(""); // returns  0
"Blue Whale".indexOf("", 9); // returns  9
"Blue Whale".indexOf("", 10); // returns 10
"Blue Whale".indexOf("", 11); // returns 10

문자열내 지정된 문자열의 마지막 위치 확인
searchString : 찾고자하는 문자열(정규식 가능), stirng으로 강제 변환, 기본값 : "undefined"
옵션, position : 검색을 시작하고자 하는 위치 ( 기본 값 : 0, 문자열 길이보다 클 경우, 전체 문자열 검색 )
또한, 지정된 position와 같거나, 작은 위치 에서만 값을 찾는다.

반환값 : Index 값 ( number) 없는 경우 -1
특징 : 만약 값이 2개 이상 있을 경우, 마지막 값의 위치를 제공하고 종료 한다.
대소문자 구분

"canal".lastIndexOf("a"); // returns 3
"canal".lastIndexOf("a", 2); // returns 1
"canal".lastIndexOf("a", 0); // returns -1
"canal".lastIndexOf("x"); // returns -1
"canal".lastIndexOf("c", -5); // returns 0
"canal".lastIndexOf("c", 0); // returns 0
"canal".lastIndexOf(""); // returns 5
"canal".lastIndexOf("", 2); // returns 2

문자열내 지정된 정규식에 포함되는 문자 반환
String.match(regexp)
regexp : 정규식 ( 정규식의 글로벌 옵션 g 를 작성하면, 문자열에 매치 되는 모둔값 반환, 없을 경우 첫번째 값 )
반환값 : 일치 할 경우, Array, 없을 경우 null

const paragraph = 'The quick brown fox jumps over the lazy dog. It barked.';
const regex = /[A-Z]/g;
const found = paragraph.match(regex);

console.log(found);
// Expected output: Array ["T", "I"]

문자열내 지정된 정규식에 포함되는 모든 문자 반환
String.match(regexp)
regexp : 정규식 ( 정규식의 글로벌 옵션 g 를 작성하지 않으면, 에러 발생 )
반환값 : 일치 할 경우, Array, 없을 경우 null

const regexp = /t(e)(st(\d?))/g;
const str = 'test1test2';

const array = [...str.matchAll(regexp)];

console.log(array[0]);
// Expected output: Array ["test1", "e", "st1", "1"]

console.log(array[1]);
// Expected output: Array ["test2", "e", "st2", "2"]

문자열 채우기

String.padEnd(targetLength, padStirng)
targetLength : 만들고자 하는 문자열의 길이 ( 값이 기존 문자열 보다 작거나 같으면 기존 문자열 반환 )
옵션, padStirng : 목표까지 채워둘 문자열
반환값 : stirng

const str1 = 'Breaded Mushrooms';

console.log(str1.padEnd(25, '.'));
// Expected output: "Breaded Mushrooms........"

const str2 = '200';

console.log(str2.padEnd(5));
// Expected output: "200  "

String.padStart

const str1 = '5';

console.log(str1.padStart(2, '0'));
// Expected output: "05"

const fullNumber = '2034399002125581';
const last4Digits = fullNumber.slice(-4);
const maskedNumber = last4Digits.padStart(fullNumber.length, '*');

console.log(maskedNumber);
// Expected output: "************5581"
"abc".padStart(10); // "       abc"
"abc".padStart(10, "foo"); // "foofoofabc"
"abc".padStart(6, "123465"); // "123abc"
"abc".padStart(8, "0"); // "00000abc"
"abc".padStart(1); // "abc"

String.raw
JS에서, \n 이나 특수 문자를 표현 하여 주기 위하여, ` ` 를 사용하야 하는데, raw를 사용하면 바로 가능하다.
정규식 패턴을 작성할때 유용하게 사용할수 있다.

const filePath = String.raw`C:\Development\profile\aboutme.html`;

console.log("filePath :", filePath) // C:\Development\profile\aboutme.html

템플릿 리터럴을 일반 문자열로 변환 하는 로직을 이용하여, 2개의 문자를 섞어 하나의 문자로 반환 하는 기능도 있다.

String.raw({ raw: "test" }, 0, 1, 2); // 't0e1s2t'
String.raw({ raw: "test" }, 'STRIN'); // 'tSTRINEST'

String.repeat
repeat(count)
count : 정수
지정된 문자열을 입력한 값만큼 복사 후 연결한 문자열을 반환한다.

"abc".repeat(-1); // RangeError
"abc".repeat(0); // ''
"abc".repeat(1); // 'abc'
"abc".repeat(2); // 'abcabc'
"abc".repeat(3.5); // 'abcabcabc' (count will be converted to integer)
"abc".repeat(1 / 0); // RangeError

String.replace()
replace(pattern, replacement)
pattern : 문자열 또는 정규식 이 입력 됩니다.
replacement : 문자열 or 함수

const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';

console.log(p.replace('dog', 'monkey'));
// Expected output: "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"

const regex = /Dog/i;
console.log(p.replace(regex, 'ferret'));
// Expected output: "The quick brown fox jumps over the lazy ferret. If the dog reacted, was it really lazy?"

문자열을 교체로 지정 할 경우 특징
문자열 : 문자열일 경우, pattern에 입력한 문자열을 입력한 문자열로 변환 합니다
( 2개 이상 발견시 가장 먼저 발견된것만 변경합니다, 만약 pattern에 입력된 정규식값에 /g 옵션이 있다면 모두 변경)

const text = 'Hello, world!';
const result = text.replace(/world/, 'beautiful $`');
console.log(result); // 출력: Hello, beautiful Hello, 

world를 찾은 후, 바로 직전 문자인 Hello를 $에 치환하여 반환 한다.

const text = 'Hello, world!';
const result = text.replace(/(world)/, 'beautiful $1');
console.log(result); // 출력: Hello, beautiful world!

world를 찾은 후, $1 찾은 문자열의 한단계 앞의 문자열로 치환하여 반환 합니다.

함수를 교체로 지정 할 경우 특징
함수 : pattern과 일치되는 만큼 함수를 수행 하며, 반환값이 대체 텍스트로 사용됩니다.

const text = '1234 5678 1234 9876';
const result = text.replace(/\d+/g, function(match) {
  return 'x'.repeat(match.length);
});
console.log(result); // 출력: xxxx xxxx xxxx xxxx

String.replaceAll()
replace(pattern, replacement)
pattern : 문자열 또는 정규식 이 입력 됩니다.
replacement : 문자열 or 함수

위 replace와 동일하지만, 일치하는 모든 값을 변환 합니다.

String.slice()
slice(indexStart, indexEnd)
indexStart : 첫 번째 문자의 인덱스, 숫자 (정수,음수) )
옵션, indexEnd : (추출할 문자열의 마지막 위치, 숫자 (정수, 음수) )
정규식 사용 불가

const str = 'The quick brown fox jumps over the lazy dog.';

console.log(str.slice(31));
// Expected output: "the lazy dog."

console.log(str.slice(4, 19));
// Expected output: "quick brown fox"

console.log(str.slice(-4));
// Expected output: "dog."

console.log(str.slice(-9, -5));
// Expected output: "lazy"

Stirng.split()
split(separator, limit)
separator : 문자열에서, 구분하고자 하는 문자열을 정의 합니다. 일반적으로 정규표현식을 사용합니다.
(함수도 가능 합니다.)
생략 할 경우, undefined로 호출 되며, 입력 문자열 단일 배열로 반환 됩니다.
옵션, limit : 반환될 문자열의 최대 갯수를 뜻합니다.
반환 값 : string[], Array

const myString = "Hello World. How are you doing?";
const splits = myString.split(" ", 3);

console.log(splits); // [ "Hello", "World.", "How" ]
const splitByNumber = {
  [Symbol.split](str) {
    let num = 1;
    let pos = 0;
    const result = [];
    while (pos < str.length) {
      const matchPos = str.indexOf(num, pos);
      if (matchPos === -1) {
        result.push(str.substring(pos));
        break;
      }
      result.push(str.substring(pos, matchPos));
      pos = matchPos + String(num).length;
      num++;
    }
    return result;
  },
};

const myString = "a1bc2c5d3e4f";
console.log(myString.split(splitByNumber)); // [ "a", "bc", "c5d", "e", "f" ]

String.substring()
substring(indexStart, indexEnd)
indexStart : 반환된 하위 문자열에 포함할 첫번째 문자열의 위치
옵션, indexEnd : 포함하고자 하는 문자열의 마지막 위치 ( 없을 경우, 문자열의 마지막 까지 )
반환 값 : String

const anyString = "Mozilla";

console.log(anyString.substring(0, 1)); // 'M'
console.log(anyString.substring(1, 0)); // 'M'

console.log(anyString.substring(0, 6)); // 'Mozill'

console.log(anyString.substring(4)); // 'lla'
console.log(anyString.substring(4, 7)); // 'lla'
console.log(anyString.substring(7, 4)); // 'lla'

console.log(anyString.substring(0, 7)); // 'Mozilla'
console.log(anyString.substring(0, 10)); // 'Mozilla'

console.log(anyString.substring(anyString.length - 4)); // prints "illa"

console.log(anyString.substring(anyString.length - 5)); // prints "zilla"

String.toLowerCase() : 주어진 문자열에 있는 대문자를 소문자로 변환하여 문자열로 반환 합니다.

const sentence = 'The quick brown fox jumps over the lazy dog.';

console.log(sentence.toLowerCase());
// Expected output: "the quick brown fox jumps over the lazy dog."

String.toUpperCase() : 주어진 문자열에 있는 소문자를 대문자로 변환하여 문자열로 반환 합니다.

const sentence = 'The quick brown fox jumps over the lazy dog.';

console.log(sentence.toUpperCase());
// Expected output: "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG."

String.trim() : 문자열 내 공백을 모두 제거후 반환 합니다.

const greeting = '   Hello world!   ';

console.log(greeting);
// Expected output: "   Hello world!   ";

console.log(greeting.trim());
// Expected output: "Hello world!";

String.trimEnd() : 문자열의 공백중 오른쪽에 있는 공백만을 제외 하고 반환 합니다. ( === Stirng.trimRight() )

const greeting = '   Hello world!   ';

console.log(greeting);
// Expected output: "   Hello world!   ";

console.log(greeting.trimEnd());
// Expected output: "   Hello world!";

String.trimStart() : 문자열의 공백중 왼쪽에 있는 공백만을 제외 하고 반환 합니다. ( === Stirng.trimLeft() )

const greeting = '   Hello world!   ';

console.log(greeting);
// Expected output: "   Hello world!   ";

console.log(greeting.trimStart());
// Expected output: "Hello world!   ";

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/String

댓글

이름만 적고 남길 수 있어요