본문 바로가기

Programming/JavaScript

Strings and Template Literals

JavaScript ES6 기준

const firstName = 'Sunny';
const job = 'technical writer';
const birthYear = 1988;
const year = 2022;

const sunny = "'I'm " + firstName + ', a ' + (year - birthYear) + ' years old ' + job + '!';
console.log(sunny);
// print 'I'm Sunny, a 34 years old technical writer!

 

그런데 위에서 불편한 점은 스페이스 바를 매번 manually 한칸씩 해줘야 함

똑같은 결과가 나오되 자동으로 스페이스바 넣어주려면?

const sunnyNew = `I'm ${firstName}, a ${year - birthYear} year old ${job}!`;
console.log(sunnyNew);

 

참고로 mac 키보드에서 backtick(`) 입력하려면 option + ₩(~) 누르면 됨!

console.log(`Just a regular string입니다.`);
// print Just a regular string입니다.

 

single quote말고 ` 해주면 매 줄넘김마다 \n\ 안해줘도 됨

console.log('String with \n\
multiple \n\
lines');
// print
// String with 
// multiple 
// lines

console.log(`String
multiple
lines`);

// print
// String
// multiple
// lines

 

'Programming > JavaScript' 카테고리의 다른 글

Coding Challenge #2 - BMI Comparison using if / else statements  (0) 2022.08.21
Taking Decisions: if / else Statements  (0) 2022.08.16
Coding Challenge #1 - BMI Comparison  (0) 2022.07.10
Operator Precedence  (0) 2022.07.10
Basic Operators  (0) 2022.07.10