javascript,HTML,CSS
[ES6] 문자열과 이스케이프
코린이예요
2019. 6. 13. 18:00
반응형
문자열 사용시 문자열의 리터럴에는 작은따옴표(')큰 따옴표("), 백틱(`)을 사용한다.
const a ='Sam looked up, and said "hello, old friend!", as Max walked in.'
const b ="Don't do that!"
* 작은따옴표를 사용하든 따옴표를 사용하든 반드시 해당 리터럴에는 한가지만 있어야 한다.
예를들어
const c = "sam looked up and said "don't do that!" to Max."
와 같이 사용하면 에러가 발생한다.
"sam looked up and said "don't do that!" to Max."
"로 시작했으면 반드시 문자열이 끝날 때 "로 끝나야 하기 때문이다.
이때 이스케이프가 필요하다.
여기서 중간에 쓰인 "앞에 역슬래시(\)를 붙여서 문자열이 끝나지 않음을 나타낸다.
const c = "sam looked up and said \"don't do that!\" to Max."
"sam looked up and said \"don't do that!\" to Max."
역슬래시(\)도 마찬가지로 문자로 사용할때는 앞에 역슬래시(\)를 한번 더붙이면 됨.
const d = "In JavaScript, use \\ as an escape character in strings.";
참고로 어떠한 텍스트를 쓸때에는 문장에서 don't와 같이 작은 따옴표를 사용하는 경우가 있으니 큰 따옴표로 감싸주는것이 좋고,
HTML을 쓸때에는 작은따옴표로 감싸주는것을 추천한다.
const a = " const c = "sam looked up and said \"don't do that!\" to Max."
const b = '<html><head>hello</head></html>'
문자열을 변수 or 상수와 같이 사용하는 방법
ES6 전 : + 기호를 사용
let currentTemp = 20;
const message = "The current temperature is " + currentTemp ;
ES6 후 : 백틱과 ${} 기호 사용
let currentTemp = 20;
const message = 'The current temperature is ${currentTemp}`;
Reference : 러닝 자바스크립트 책 (이선 브라운 지음)
반응형