不会缩进缩进的多行字符串 [英] Multiline strings that don't break indentation

查看:64
本文介绍了不会缩进缩进的多行字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据

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 beginning of the line.

Allen Wirfs-Brock’s post contains a code example:

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`;

Could someone explain how this can be achieved? How to define this dontIndent thing in order to remove the whitespace used for indentation?

解决方案

2020 answer: there is still nothing built into the JS stdlib to handle de-denting long lines, although TC39 has discussed adding a new template literal that handles indentation. You have 2 options presently:

  1. The endent and dedent-js packages will handle this. Note the dedent-js package actually works with both tabs and spaces, dedent is a separate package and fails on tabs:

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

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

Will strip out the proceeding whitespace on each line and the leading carriage return. It also has more users, an issue tracker, and is more easily updated than copypasting from Stack Overflow!

  1. Don't indent long lines, but use an editor that shows long lines as indented. Eg, vsCode - you can simply use long lines, not indent anything, and include carriage returns in a long string. vsCode will show them indented. The string below has no indentation - the second line The empty export... is immediately after the carriage return, but shows up as indented.

这篇关于不会缩进缩进的多行字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆