Multiline strings that don't break indentation

前端 未结 5 1403
离开以前
离开以前 2020-12-30 18:32

According to this esdiscuss discussion, it is possible in ECMAScript 6 to define multiline strings without having to place subsequent lines of the string at the very beginni

5条回答
  •  攒了一身酷
    2020-12-30 19:14

    How to define this dontIndent thing in order to remove the whitespace used for indentation?

    I suppose something like this should suffice for many cases (including the OP):

    function dontIndent(str){
      return ('' + str).replace(/(\n)\s+/g, '$1');
    }
    

    Demo code in this snippet:

    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`;
    
    console.log(a);
             
    function dontIndent(str){
      return ('' + str).replace(/(\n)\s+/g, '$1');
    }

    Explanation

    JavaScript template literals can be called with a tag, which in this example is dontIndent. Tags are defined as functions, and are called with the template literal as an argument, so we define a dontIndent() function. The template literal is passed as an argument in an array, so we use the expression ('' + str) to cast the array content to a string. Then, we can use a regular expression like /(\n)\s+/g to .replace() all occurrences of line breaks followed by white space with only the line break to achieve the aim of the OP.

提交回复
热议问题