Multiline strings that don't break indentation

那年仲夏 提交于 2019-11-30 10:50:44

This feature is implemented by defining a custom function and then using it as a tag (dontIndent above). The code blow is from 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);
}

I've successfully tested it in Firefox Nightly:

2016 answer: the dedent-js package 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!

You can also just do a string replace for double spaces (assuming your indentation uses spaces, not tabs). Obviously any double spaces in your actual string would be removed, but for most cases this should be ok.

const MSG = (`Line 1
          line 2
          line 3`).replace(/  +/g, '');
// outputs
/*
Line 1
line 2
line 3
*/
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!