본문 바로가기
공부/javascript

2022.04.28 - javascript 템플릿 리터럴, 문자열 메서드

by 기묜몬 2022. 4. 28.

- ES6 에서의 문자열 삽입

백틱(`)을 사용하여 코드를 더 쉽게 작성할 수 있게 되었다. 

let name = "Alberto";
const greeting = `Hello my name is ${name}`;

console.log(greeting);
//Hello my name is Alberto

- 표현식 삽입

var a = 1;
var b = 10;
console.log(`1* 10 is ${a+b}`);

// 1*10 is 10

 

[ 문자열 메서드 ]

 

- indexOf() : 문자열에서 지정된 값이 처음 나타나는 위치를 반환한다. 

const str = "this is a short sentence";
str.indexOf("short");

console.log(str.indexOf("short")); 
// 출력 10

 

- slice() : 문자열의 지정된 부분을 새 문자열로 반환한다. 

const str = "pizza, orange, cereals";
str.slice(0, 5);

console.log(str.slice(0, 5));
// "pizza"

 

- toUpperCase() : 문자열 내의 모든 문자를 대문자로 바꾼다. 

const str = "i ate an apple";

console.log(str.toUpperCase());
//"I ATE AN APPLE"

 

- toLowerCase() :  문자열의 모든 문자를 소문자로 바꾼다. 

const str = "I ATE AN APPLE";

console.log(str.toLowerCase());
//i ate an apple

 

* ES6 는 4가지 새로운 문자열 메서드를 도입했다. 

startsWith()

endsWith()

includes()

repeat()

 

- startsWith() : 매개변수로 받은 값으로 문자열이 시작하는지 확인한다. 

const code = "ABCDEFG";

console.log(code.startsWith("ABB"));
// false
console.log(code.startsWith("abc"));
// false / startsWith()는 대소문자를 구분한다. 
console.log(code.startsWith("ABC"));
// true

 

- endsWith() :  startsWith()와 유사하게 문자열이 우리가 전달한 값으로 끝나는지 확인한다. 

const code = "ABCDEFG";

console.log(code.endsWith("EFF"));
// false
console.log(code.endsWith("efg"));
// false endsWith()는 대소문자를 구분한다. 
console.log(code.endsWith("EFG"));
// true

- 추가 매개변수로 문자열의 얼마큰만을 확인할지 길이를 전달할 수 있다. endsWith() 

const code = "ABCDEFGHI";

console.log(code.endsWith("EF",6));
// true 첫 6개 문자인 ABCDEF만을 고려하며, ABCDEF는 EF로 끝나므로 true

 

- includes() : 우리가 전달한 값이 문자열에 포함되어 있는지 확인한다. 

const code = "ABCDEFG";

console.log(code.includes("ABB"));
// false 
console.log(code.includes("BCD"));
// true
console.log(code.includes("bcd"));
// false includes()는 대소문자를 구분한다.

 

- repeat() : 문자열을 반복하며 횟수를 인수로 받는다. 

let hello = "Hi";
console.log(hello.repeat(10));
//HiHiHiHiHiHiHiHiHiHi