본문 바로가기
정리_창고

JavaScript - String Methods 사전식 정리

by SKim입니다 2020. 7. 5.

JavaScript 총정리 - 목차로 바로가기

 

charAt()  str.charAt(index)

문자열 안에 specified index에 위치한 character를 리턴한다.

더보기

리턴값: specified index에 위치한 character를 나타내는 문자열. 만약 그 index 번호가 없다면 빈 문자열.

index - 리턴하고 싶은 character의 index를 나타내는 정수 (디폴트: 0)

 

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

console.log(`The character at index ${index} is ${sentence.charAt(index)}`);
// expected output: "The character at index 4 is q"

 

charCodeAt()  str.charCodeAt(index)

specified index에 위치한 character의 유니코드를 리턴한다.

더보기

리턴값: specified index에 위치한 character의 유니코드를 나타내는 숫자. 만약 그 specified index에 character가존재하지 않거나, 그 index가 0보다 작다면 "NaN"을 리턴한다.

index - 리턴하고 싶은 character의 index를 나타내는 정수 (디폴트: 0)

 

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

console.log(`The character code ${sentence.charCodeAt(index)} is equal to ${sentence.charAt(index)}`);
// expected output: "The character code 113 is equal to q"

 

concat()  str.concat(string2, string3[, ..., stringN])

두 개 이상의 문자열을 join하고, join된 새로운 문자열을 리턴한다.

더보기

리턴값: combine된 문자열들의 텍스트를 담고 있는 새로운 문자열.

string - join될 문자열

 

* 기존의 문자열을 변경하지 않는다.

 

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

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

 

constructor   str.constructor

그 문자열의 constructor 함수를 리턴한다.

더보기

리턴값: function String() { [native code] }

constructor property는 object의 constructor 함수를 리턴한다.

리턴값은 그 함수의 이름이 아니라, 그 함수의 reference이다.

 

var str = "Hello World!";
str.constructor;

// function String() { [native code] }

 

endsWith()  str.endsWith(searchString[, length])

문자열이 specified 문자열/characters로 끝나는지 체크한다.

더보기

리턴값: 불리언. 그 문자열이 그 값으로 끝나면 true를, 그렇지 않으면 false를 리턴한다.

searchString - 탐색할 문자열

length - 탐색할 문자열(str - to search)의 길이를 specify한다. (디폴트: 그 문자열의 길이)

 

* 대소문자를 구분한다.

 

var str = 'To be, or not to be, that is the question.';

console.log(str.endsWith('question.')); // true
console.log(str.endsWith('to be'));     // false
console.log(str.endsWith('to be', 19)); // true
// str을 19번째 글자까지 자른 결과는 'to be'로 끝난다.

 

fromCharCode()  String.fromCharCode(num1[, ...[, numN]])

유니코드 값들을 character들로 변환한다.

더보기

리턴값: specified 유니코드 숫자를 나타내는 charater(들)을 나타내는 문자열.

num - 변환할 유니코드 값 한 개 이상

 

var res = String.fromCharCode(72, 69, 76, 76, 79);
// HELLO

 

includes()  str.includes(searchString[, position])

문자열이 specified 문자열/characters를 포함하는지 체크한다.

더보기

리턴값: 불리언. 그 문자열이 그 값을 포함하면 true, 아니면 false를 리턴한다.

searchString - 탐색할(search for) 문자열

position - 탐색을 시작할 위치 (디폴트: 0)

 

* 대소문자를 구분한다.

 

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

console.log(`The word "${word}" ${sentence.includes(word) ? 'is' : 'is not'} in the sentence`);
// expected output: "The word "fox" is in the sentence"

 

indexOf()  str.indexOf(searchValue[, fromIndex])

문자열 안에서 specified 값이 처음 나타나는 위치를 리턴한다.

더보기

리턴값: specified serachValue가 처음으로 나타나는 곳의 위치를 나타내는 숫자. 나타나지 않으면 -1.

searchValue - 탐색할 (search for) 문자열

fromIndex - 탐색을 시작할 위치. (디폴트: 0)

 

* 대소문자를 구분한다.

 

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

const searchTerm = 'dog';
const indexOfFirst = paragraph.indexOf(searchTerm);

console.log(`The index of the first "${searchTerm}" from the beginning is ${indexOfFirst}`);
// expected output: "The index of the first "dog" from the beginning is 40"

console.log(`The index of the 2nd "${searchTerm}" is ${paragraph.indexOf(searchTerm, (indexOfFirst + 1))}`);
// expected output: "The index of the 2nd "dog" is 52"

 

lastIndexOf()  str.lastIndexOf(searchValue[, fromIndex])

문자열 안에서 specified 값이 마지막으로 나타나는 위치를 리턴한다.

더보기

리턴값: specified serachValue가 마지막으로 나타나는 곳의 위치를 나타내는 숫자. 나타나지 않으면 -1.

searchValue - 탐색할 (search for) 문자열

fromIndex - 탐색을 시작할 위치. 탐색은 뒤에서부터 한다. (디폴트: 그 문자열의 길이)

 

* 대소문자를 구분한다.

 

'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

 

length   str.length

문자열의 길이를 리턴한다.

더보기

리턴값: 문자열의 길이

 

const str = 'Life, the universe and everything. Answer:';

console.log(`${str} ${str.length}`);
// expected output: "Life, the universe and everything. Answer: 42"

 

localeCompare()  referenceStr.localeCompare(compareString[, locales[, options]])

두 문자열을 current locale에서 비교한다.

더보기

리턴값: sort order에 따라서 compareString과 비교했을 때, 레퍼런스 문자열이 그보다 뒤에/앞에 오는지 또는 같은지 나타내는 숫자.

- compareString 다음에 레퍼런스 문자열이 sort된다면 1

- 레퍼런스 문자열 다음에 compareString이 sort된다면 -1

- 두 문자열이 같다면 0

compareString - 비교할 (compare with) 문자열

 

locale은 그 브라우저의 언어 설정에 기초한다.

 

// The letter "a" is before "c" yielding a negative value
'a'.localeCompare('c'); // -2 or -1 (or some other negative value)

// Alphabetically the word "check" comes after "against" yielding a positive value
'check'.localeCompare('against'); // 2 or 1 (or some other positive value)

// "a" and "a" are equivalent yielding a neutral value of zero
'a'.localeCompare('a'); // 0

 

match()  str.match(regexp)

문자열이 정규표현식과 매치되는지 탐색하고, 그 매치들을 Array object로 리턴한다.

더보기

리턴값: 매치들을 포함하는 배열. 각각의 매치마다 하나의 item. 매치가 없다면 null을 리턴한다.

regexp - 탐색할 (search for) 값을 정규표현식으로 나타낸 것

 

* 만약 정규표현식에 g modifier(global search)를 붙이지 않는다면 첫 번째 매치만 리턴한다.

 

var str = 'For more information, see Chapter 3.4.5.1';
var re = /see (chapter \d+(\.\d)*)/i;
var found = str.match(re);

console.log(found);

// logs [ 'see Chapter 3.4.5.1',
//        'Chapter 3.4.5.1',
//        '.1',
//        index: 22,
//        input: 'For more information, see Chapter 3.4.5.1' ]

// 'see Chapter 3.4.5.1'는 완전한 매치 상태임.
// 'Chapter 3.4.5.1'는 '(chapter \d+(\.\d)*)' 부분에 의해 발견된 것임.
// '.1' 는 '(\.\d)'를 통해 매치된 마지막 값임.
// 'index' 요소가 (22)라는 것은 0에서부터 셀 때 22번째 위치부터 완전 매치된 문자열이 나타남을 의미함.
// 'input' 요소는 입력된 원래 문자열을 나타냄.

 

prototype   object.prototype.name = value

object type에 새로운 property들과 메소드들을 추가할 수 있게 해준다.

더보기

리턴값: String.prototype object에 대한 레퍼런스


repeat()  str.repeat(count);

문자열이 specified 횟수만큼 반복된 복사본으로 만든 새로운 문자열을 리턴한다.

더보기

리턴값: original 문자열의 복사본들을 갖고 있는 새로운 문자열

count - 새로운 문자열에서 original 문자열 값이 몇 번 반복될 것인가를 나타내는 숫자

 

'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

({ toString: () => 'abc', repeat: String.prototype.repeat }).repeat(2);
// 'abcabc' (repeat() is a generic method)

 

replace()  var newStr = str.replace(regexp|substr, newSubstr|function)

문자열에 specified 값/정규표현식이 있는지 탐색하고, specified 값이 대체된 새로운 문자열을 리턴한다.

더보기

리턴값: specify된 값(들)이 새로운 값으로 대체된 새로운 문자열.

regexp | substr - 새로운 값에 의해 대체될 정규표현식이나 값

newSubstr | function - 위의 것을 대체할 값

 

* 만약 정규표현식이 아닌 그냥 값을 쓰면, 첫 번째 값만이 대체된다. 모든 값을 specify된 값으로 대체하려면, g(global) modifier를 사용한다.

* original 문자열을 변경하지 않는다.

 

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

const regex = /dog/gi;

console.log(p.replace(regex, 'ferret'));
// expected output: "The quick brown fox jumps over the lazy ferret. If the ferret 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?"

 

search()  str.search(regexp)

문자열에 specified 값/정규표현식이 있는지 탐색하고, 그 매치의 위치를 리턴한다.

더보기

리턴값: specify된 정규표현식이 처음으로 등장하는 위치를 나타내는 숫자. 매치가 없다면 -1.

regexp - 정규표현식. 문자열을 쓰면 자동으로 정규표현식으로 변환된다.

 

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

// any character that is not a word character or whitespace
const regex = /[^\w\s]/g;

console.log(paragraph.search(regex));
// expected output: 43

console.log(paragraph[paragraph.search(regex)]);
// expected output: "."

 

slice()  str.slice(beginIndex[, endIndex])

문자열의 부분을 추출해서 새로운 문자열을 리턴한다.

더보기

리턴값: 그 문자열의 추출된 부분을 나타내는 문자열

beginIndex - 추출을 시작할 위치. 뒤에서부터 세려면 음수를 쓴다. (-3이라면 str.length-3과 같다.)

endIndex - 추출을 끝낼 위치 바로 다음. (디폴트: str.length)

 

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

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

 

split()  str.split([separator[, limit]])

문자열을 쪼개서 substring들의 array로 만들어서 리턴한다.

더보기

리턴값: 쪼개진 값들을 가지는 Array.

separator - 문자열을 쪼개는데 사용되는 character나 정규표현식을 specify한다. 생략하면 전체 문자열이 리턴된다. (배열 안에 하나의 item만 존재)

limit - 쪼개는 횟수를 specify하는 정수. 그 후의 item들은 배열에 포함되지 않는다.

 

* separator로 빈 문자열('')을 사용하면, 각각의 character마다 쪼개진다.

* original 문자열을 변경하지 않는다.

 

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

const words = str.split(' ');
console.log(words[3]);
// expected output: "fox"

const chars = str.split('');
console.log(chars[8]);
// expected output: "k"

const strCopy = str.split();
console.log(strCopy);
// expected output: Array ["The quick brown fox jumps over the lazy dog."]

 

startsWith()  str.startsWith(searchString[, position])

문자열이 specified characters로 시작하는지 여부를 체크한다.

더보기

리턴값: 불리언. 만약 문자열이 그 value로 시작하면 true를, 그렇지 않으면 false를 리턴한다.

searchString - 탐색할 (search for) 문자열

position - 탐색을 시작할 위치 (디폴트: 0)

 

* 대소문자를 구분한다.

 

var str = 'To be, or not to be, that is the question.';

console.log(str.startsWith('To be'));         // true
console.log(str.startsWith('not to be'));     // false
console.log(str.startsWith('not to be', 10)); // true

 

substr()  str.substr(start[, length])

문자열로부터 character들을 추출한다. - specified 시작 위치에서부터 ~ specified 갯수의 character 만큼까지

더보기

※ 없어질 수도 있는  기능

리턴값: 그 텍스트의 추출된 부분을 포함하는 새로운 문자열. 만약 length에 0이나 음수를 입력하면 빈 문자열이 리턴된다.

start - 추출을 시작할 위치.

 - 음수 - 뒤에서부터 세어서, 뒤에서부터 추출한다.

 - 음수이거나 문자열의 길이보다 크다면, start = 0으로 설정된다. 

 - 양수이고 문자열의 길이보다 같거나 크다면, 빈 문자열을 리턴한다.

length - 추출할 character의 수 (디폴트: 문자열의 끝까지)

 

* original 문자열을 변경하지 않는다.

 

const str = 'Mozilla';

console.log(str.substr(1, 2));
// expected output: "oz"

console.log(str.substr(2));
// expected output: "zilla"

 

substring()  str.substring(indexStart[, indexEnd])

문자열로부터 character들을 추출한다. - 두 개의 specified index 사이에서 → 새로운 sub 문자열을 리턴한다.

더보기

리턴값: 추출된 character들을 가지는 새로운 문자열.

indexStart - 추출을 시작할 위치

indexEnd - 추출을 끝낼 위치 바로 다음 (디폴트: 문자열의 끝까지)

 

* 만약 indexStart > indexEnd이면, 자동으로 두개의 값이 바뀌게 된다.

ex) str.substring(1, 4) == str.substring(4, 1)

* 만약 indexStart 또는 indexEnd가 0보다 작다면, 자동으로 0으로 설정된다.

* original 문자열을 변경하지 않는다.

 

const str = 'Mozilla';

console.log(str.substring(1, 3));
// expected output: "oz"

console.log(str.substring(2));
// expected output: "zilla"

 

toLocaleLowerCase()  str.toLowerCase()

문자열을 소문자 글자들로 변환한다. - host의 locale에 따라서

더보기

리턴값: host의 현재 locale에 따라서 소문자로 변환된 문자열의 값을 나타내는 문자열

 

* locale은 그 브라우저의 언어 설정에 기초한다.

* 대개 toLowerCase와 같은 결과가 리턴된다. 그러나 터키어처럼 정규적인 유니코드 대/소문자 맵핑에 문제가 있는 언어의 경우는 결과가 다를 수 있다.

* original 문자열을 변경하지 않는다.

 

toLocaleUpperCase()  str.toUpperCase()

문자열을 대문자 글자들로 변환한다. - host의 locale에 따라서

더보기

리턴값: host의 현재 locale에 따라서 대문자로 변환된 문자열의 값을 나타내는 문자열

 

* locale은 그 브라우저의 언어 설정에 기초한다.

* 대개 toUpperCase와 같은 결과가 리턴된다. 그러나 터키어처럼 정규적인 유니코드 대/소문자 맵핑에 문제가 있는 언어의 경우는 결과가 다를 수 있다.

* original 문자열을 변경하지 않는다.

 

toLowerCase()  str.toLowerCase()

문자열을 소문자 글자들로 변환한다.

더보기

리턴값: 문자열이 소문자로 변환된 값을 나타내는 문자열

* original 문자열을 변경하지 않는다.

 

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."

 

toString()  str.toString()

문자열 object의 값을 리턴한다.

더보기

리턴값: 문자열의 값을 나타내는 문자열

* String object의 값을 리턴한다.

* Number 메소드에 진법 변환까지 나온다.

 

const stringObj = new String('foo');

console.log(stringObj);
// expected output: String { "foo" }

console.log(stringObj.toString());
// expected output: "foo"

 

toUpperCase()  str.toUpperCase()

문자열을 대문자 글자들로 변환한다.

더보기

리턴값: 문자열이 대문자로 변환된 값을 나타내는 문자열

* original 문자열을 변경하지 않는다.

 

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."

 

trim()  str.trim()

문자열의 양옆의 공백을 제거한다.

더보기

리턴값: 양옆의 공백을 제거한 문자열을 나타내는 문자열

 

* original 문자열을 변경하지 않는다.

* str.trimStart() = str.trimLeft()   /   str.trimEnd(); = str.trimRight(); 

 

const greeting = '   Hello world!   ';

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

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

 

valueOf()  str.valueOf()

문자열 object의 primitive 값을 리턴한다.

더보기

리턴값: 문자열의 primitive 값을 나타내는 문자열

 

* 이 메소드는 주로 JavaScript에 의해서 자동적으로 호출되고, 코드에는 명시적으로 보이지 않는다.

 

const stringObj = new String('foo');

console.log(stringObj);
// expected output: String { "foo" }

console.log(stringObj.valueOf());
// expected output: "foo"

 

 

 

< 출처 >

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String

 

String

String 전역 객체는 문자열(문자의 나열)의 생성자입니다.

developer.mozilla.org

https://www.w3schools.com/jsref/jsref_obj_string.asp

 

JavaScript String Reference

JavaScript String Reference JavaScript Strings A JavaScript string stores a series of characters like "John Doe". A string can be any text inside double or single quotes: String indexes are zero-based: The first character is in position 0, the second in 1,

www.w3schools.com

 

댓글