es6 템플릿 리터럴에서 문자열에 새 줄을 만들지 않고 긴 템플릿 리터럴을 여러 줄로 줄 바꿈하는 방법은 무엇입니까?
예를 들어, 이렇게하면 :
const text = `a very long string that just continues
and continues and continues`
그런 다음 새 줄이있는 것으로 해석하여 문자열에 새 줄 기호를 만듭니다. 줄 바꿈을 만들지 않고 긴 템플릿 리터럴을 여러 줄로 어떻게 묶을 수 있습니까?
답변
리터럴에서 줄 바꿈 지점에 줄 연속 ( \
) 을 도입하면 출력에 줄 바꿈이 생성되지 않습니다.
const text = `a very long string that just continues\
and continues and continues`;
console.log(text); // a very long string that just continuesand continues and continues
답변
이것은 오래된 것입니다. 그러나 그것은 나타났다. 편집기에 공백을 남겨두면 공백이 배치됩니다.
if
const text = `a very long string that just continues\
and continues and continues`;
그냥 일반 + 기호를 수행하십시오.
if
const text = `a very long string that just continues` +
`and continues and continues`;
답변
템플릿 리터럴 내부에서 줄 바꿈을 먹을 수 있습니다.
// Thanks to https://twitter.com/awbjs for introducing me to the idea
// here: https://esdiscuss.org/topic/multiline-template-strings-that-don-t-break-indentation
const printLongLine = continues => {
const text = `a very long string that just ${continues}${''
} and ${continues} and ${continues}`;
return text;
}
console.log(printLongLine('continues'));
답변
편집 :이 유틸리티를 사용하여 작은 NPM 모듈을 만들었습니다. 그것은 웹과 노드에서 작동하며 훨씬 강력하기 때문에 아래 답변의 코드보다 강력하게 권장합니다. 또한으로 수동으로 입력하면 결과에 줄 바꿈을 유지할 수 있으며 \n
이미 다른 것에 템플릿 리터럴 태그를 사용하는 경우 기능을 제공합니다. https://github.com/iansan5653/compress-tag
나는 여기에 대답하기 늦었다는 것을 알고 있지만 받아 들인 대답은 여전히 줄 바꿈 후에 들여 쓰기를 허용하지 않는 단점이 있습니다. 즉, 줄 바꿈을 빠져서도 아주 멋진 코드를 작성할 수는 없습니다.
대신 태그 가 지정된 템플릿 리터럴 함수를 사용하지 않는 이유는 무엇입니까?
function noWhiteSpace(strings, ...placeholders) {
// Build the string as normal, combining all the strings and placeholders:
let withSpace = strings.reduce((result, string, i) => (result + placeholders[i - 1] + string));
let withoutSpace = withSpace.replace(/\s\s+/g, ' ');
return withoutSpace;
}
그런 다음 줄 바꿈하려는 템플릿 리터럴에 태그를 지정할 수 있습니다.
let myString = noWhiteSpace`This is a really long string, that needs to wrap over
several lines. With a normal template literal you can't do that, but you can
use a template literal tag to allow line breaks and indents.`;
미래 개발자가 태그가 지정된 템플릿 구문에 익숙하지 않거나 설명 함수 이름을 사용하지 않는 경우 예상치 못한 동작이 발생할 수 있지만 현재로서는 가장 깨끗한 솔루션 인 것 같습니다.
답변
다른 옵션은 Array.join
다음과 같이 사용하는 것입니다.
[
'This is a very long string. ',
'It just keeps going ',
'and going ',
'and going ',
'and going ',
'and going ',
'and going ',
'and going',
].join('')
답변
오래된 것과 새로운 것을 사용하십시오. 템플릿 리터럴은 훌륭하지만 간단한 코드 줄을 유지하기 위해 긴 리터럴을 피하려면 연결하고 ESLint는 소란을 일으키지 않습니다.
const text = `a very long string that just continues`
+` and continues and continues`;
console.log(text);
답변
Doug의 답변과 마찬가지로 이것은 TSLint 구성에서 허용되며 IntelliJ 자동 포맷터에서 그대로 유지됩니다.
const text = `a very long string that just ${
continues
} and ${continues} and ${continues}`
