program story

문자열에 새 줄을 만들지 않고 긴 템플릿 리터럴 줄을 여러 줄로 줄 바꿈

inputbox 2020. 8. 9. 10:25
반응형

문자열에 새 줄을 만들지 않고 긴 템플릿 리터럴 줄을 여러 줄로 줄 바꿈


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 모듈을 만들었습니다. 그것은 웹과 Node에서 작동하며 훨씬 더 강력하기 때문에 아래 답변의 코드보다 적극 권장합니다. 또한 수동으로으로 입력하면 결과에 줄 바꿈을 유지할 수 있으며 \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.`;

이것은 미래의 개발자가 태그 된 템플릿 구문에 익숙하지 않거나 설명적인 함수 이름을 사용하지 않는 경우 예기치 않은 동작이 발생할 수 있다는 단점이 있지만 지금은 가장 깨끗한 솔루션처럼 느껴집니다.


오래된 것과 새로운 것을 사용하십시오. 템플릿 리터럴은 훌륭하지만 코드 줄을 간결하게 만들기 위해 긴 리터럴을 피하려면 이들을 연결하면 ESLint가 소란스럽지 않습니다.

const text = `a very long string that just continues`
  +` and continues and continues`;
console.log(text);

@CodingIntrigue가 제안한 솔루션은 노드 7에서 작동하지 않습니다. 음, 첫 번째 줄에서 줄 연속을 사용하지 않으면 작동하고 그렇지 않으면 실패합니다.

이것이 최선의 해결책은 아니지만 문제없이 작동합니다.

(`
    border:1px solid blue;
    border-radius:10px;
    padding: 14px 25px;
    text-decoration:none;
    display: inline-block;
    text-align: center;`).replace(/\n/g,'').trim();

참고 URL : https://stackoverflow.com/questions/37321047/wrap-long-template-literal-line-to-multiline-without-creating-a-new-line-in-the

반응형