문자열 관련 Methods

Blackwidow·2020년 12월 1일
1
post-thumbnail

아래 메소드들은 mdn이라는 자바스크립트 관련 사전과 같은 싸이트에서 검색할 수 있다.

!!!모든 string methodsms immutable(변경되지 않는다)!!!

1. String(thing)
(thing)안에 타입을 문자열로 변경한다.

String("hello") // "hello"
String(123) // "123"
String(true) //"true"

2. substring()
string 객체의 시작인덱스에서 종료인덱스 전(!)까지 문자열의 부분 문자열을 반환한다.sub은 '부분'이라고 해석하면 편하다.

const str = 'Mozilla';

console.log(str.substring(1, 3)); //"oz"
//index 1부터 index3까지 문자열만 반환

console.log(str.substring(0, 5)); //"Mozil"
// index 0부터 index5문자열만 반

console.log(str.substring(2)); //"zilla"
//index2번까지 제외하고 나머지 문자열 출력

console.log(str.substring(7)); //""
//문자열의 마지막 index가 7이므로 빈문자열 반환

console.log(str.substring(8)); //""
//문자열의 최종 index인 7 이상을 값으로 넣으면 빈문자열을 반환하는것을 알 수 있다.

console.log(str.substring(0)); //"Mozilla"
//문자열을 다 출력하고 싶을때에는 index0을 넣으면 문자가 시작되기 전의 인덱스이기 때문에 모두 출력

3. toUpperCase()
toUpperCase() 메소드는 문자열을 대문자로 변환해 반환한다.

const sentence = 'I am a software engineer.';
console.log(sentence.toUpperCase()); //  "I AM A SOFTWARE ENGINEER."

4. toLowerCase()
toUpperCase() 메소드는 문자열을 소문자로 변환해 반환한다.

const sentence = 'I AM A SOFTWARE ENGINEER.';
console.log(sentence.toLowerCase()); // "i am a software engineer."

5. indexOf()
indexOf() 메소드는 문자열에서 해당 문자의 번째(index)를 찾아서 반환하고 존재하지 않으면 -1을 반환한다.

const alphabet = 'abc def abc'

console.log(alphabet.indexOf('a')); // 0
console.log(alphabet.indexOf('b')); // 1 
// alphabet변수에는 b가 총 2개이지만 처음 등장하는 index를 출력한다.
console.log(alphabet.indexOf('c')); // 2
//c도 b와 동일하게 처음 등장하는 index 출력한다.
console.log(alphabet.indexOf('z')); // -1
//없는 문자열의 index를 찾을때에는 -1을 출력한다.

5-1. lastIndexOf()
indexOf() 메소드와 같은 기능이지만 문자열의 처음이 아닌 마지막부터 index를 찾는다.

const alphabet = 'abc def abc'

console.log(alphabet.lastIndexOf('a')); // 8
//문자열 뒤에서 시작하여 index를 찾고 index는 그대로 리턴한다.

6. includes()
includes() 메소드는 해당값이 문자열에 포함하고 있는지 판별한다.

const String = '123'

console.log(String.includes(1)); // true
console.log(String.includes(2)); // true
console.log(String.includes(10)); // true
console.log(String.includes('a')); // false

하지만 includes() 메소드는 브라우저 호환성에서 Internet Explorer에서는 작동하지 않고 에러 발생. -> indexOf()사용 권장.

7. concat()
concat() 메소드는 매개변수(str1)로 전달된 모든 문자열을 호출 문자열(str2)에 붙인 new문자열을 반환한다.

const str1 = 'Apple';
const str2 = 'Banana';

console.log(str1.concat(str2)); // "AppleBanana"
console.log(str1.concat(' ', str2)); // "Apple Banana"
console.log(str2.concat(', ', str1)); // "Banana, Apple"

8. split()
split() 매소드는 String객체를 지정하고 ()안의 구분자를 기준으로 나눠서 여러개의 문자열로 바꾸어주고 String을 배열로 변환해준다.

const str = 'I am a software engineer';

const words = str.split(' '); 
console.log(words); // ["I", "am", "a", "software", "engineer"]
console.log(words[0]); //  "I"

const chars = str.split('');
console.log(chars); //["I", " ", "a", "m", " ", "a", " ", "s", "o", "f", "t", "w", "a", "r", "e", " ", "e", "n", "g", "i", "n", "e", "e", "r"]
console.log(chars[3]); // "m"

const strCopy = str.split(); 
console.log(strCopy); // ["I am a software engineer"]
console.log(strCopy[0]); // "I am a software engineer"
console.log(strCopy[2]); // undefined
  • csv(comma-separated values)형식을 처리할때 유용
let csv = `연도, 제조사, 모델, 설명, 가격
2001, Ford, E350,"ac, abs, moon",3000
2007, Chevy, "Venture ""Extended Edition""","",4900`;

csv.split(','); 
// ["연도", " 제조사", " 모델", " 설명", " 가격↵2001", " Ford", " E350", ""ac", " abs", " moon"", "3000↵2007", " Chevy", " "Venture ""Extended Edition"""", """", "4900"]
// 콤마(,)기준으로 나눠서 배열로 출력하였다.

csv.split('\n'); 
// 0: "연도, 제조사, 모델, 설명, 가격"
   1: "2001, Ford, E350,"ac, abs, moon",3000"
   2: "2007, Chevy, "Venture ""Extended Edition""","",4900"
   length: 3
// 줄바꿈(\n)을 기준으로 나눠서 배열로 출력하였다.

let lines = csv.split('\n'); //csv문자열을 줄바꿈 기준으로 나눈것을 lines변수에 넣고

lines[0]; // "연도, 제조사, 모델, 설명, 가격"
lines[1]; // "2001, Ford, E350,"ac, abs, moon",3000"

//다시 lines의 0번째를 콤마(,)로 나누면?
lines[0].split(','); 
// ["연도", " 제조사", " 모델", " 설명", " 가격"]
// 배열로 출력된다.

9. trim()
trim()메소드는 문자열의 양 끝의 공백(처음과 끝)을 제거한다.
이 때, 공백이란 모든 공백문자(space, tab(\t), NBSP(공백을 주기 위한 특수문자), return문자(\n) 등)와 모든 개행문자를 의미한다.

const greeting = '   Hello world!   ';

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

10. slice()
slice()메소드는 문자열의 처음부터 끝까지(끝 미포함)에 대해 복사본을 새로운 객체로 반환한다. 원본은 변하지 않는다.
(배열과 문자열 다 사용 가능)

const animals = 'Apple';

console.log(animals.slice(1)); // "pple"

console.log(animals.slice(0, 2)); // "Ap"

console.log(animals.slice(1, 3)); // "pp"

11. join()
join() 메소드는 배열의 모든 요소를 연결해 하나의 문자열로 만든다.

const elements = ['Fire', 'Air', 'Water'];

console.log(elements.join()); // "Fire,Air,Water"


console.log(elements.join(' ')); // "Fire Air Water"


console.log(elements.join('-')); // "Fire-Air-Water"
profile
javascript 공부하는 sumiindaeyo

0개의 댓글