2014-09-18 3 views
21

this esdiscuss discussion에 따르면 ECMAScript 6에서는 줄의 맨 처음에 문자열의 후속 줄을 배치 할 필요없이 여러 줄을 정의 할 수 있습니다.들여 쓰기를 끊지 않는 여러 줄 문자열

var a = dontIndent 
     `This is a template string. 
     Even though each line is indented to keep the 
     code neat and tidy, the white space used to indent 
     is not in the resulting string`; 

사람이 달성 할 수있는 방법을 설명 할 수 :

Allen Wirfs-Brock’s post

코드 예제를 포함? 들여 쓰기에 사용 된 공백을 제거하기 위해 이것을 dontIndent 것으로 정의하는 방법은 무엇입니까?

+2

이제는 npm에 여러 개의 모듈이 있습니다. 대부분은 "dedent"에 대한 키워드 검색을 통해 찾을 수 있습니다 (https://www.npmjs.com/browse/keyword/dedent) – Nickolay

답변

13

이 기능은 사용자 지정 함수를 정의한 다음 태그 (dontIndent 위)로 사용하여 구현됩니다. 코드 타격 Zenparsing's gist에서이다 : 나는 성공적으로 파이어 폭스 박에서 테스트 한

function dedent(callSite, ...args) { 

    function format(str) { 

     let size = -1; 

     return str.replace(/\n(\s+)/g, (m, m1) => { 

      if (size < 0) 
       size = m1.replace(/\t/g, " ").length; 

      return "\n" + m1.slice(Math.min(m1.length, size)); 
     }); 
    } 

    if (typeof callSite === "string") 
     return format(callSite); 

    if (typeof callSite === "function") 
     return (...args) => format(callSite(...args)); 

    let output = callSite 
     .slice(0, args.length + 1) 
     .map((text, i) => (i === 0 ? "" : args[i - 1]) + text) 
     .join(""); 

    return format(output); 
} 

:

enter image description here

11

2016 대답 다음 dedent-js package이 처리됩니다. 'dedent-JS'패키지가 실제로 탭과 공간 모두에서 작동합니다, 'dedent는'탭에 실패

var dedent = require('dedent-js'); 

var text = dedent(` 
    <div> 
    <span>OK</span> 
    <div> 
     <div></div> 
    </div> 
    </div> 
`); 

각 줄에 진행 공백 및 주요 캐리지 리턴을 제거 할 것이다. 또한 더 많은 사용자 (이슈 추적기)가 있으며 Stack Overflow에서 복사하는 것보다 쉽게 ​​업데이트됩니다!

+1

그게 아름답게 작동합니다, 감사합니다 당신 –

관련 문제