如何处理模板文字中无关的 white-space

how to deal with extraneous white-space in template literals

如何处理多行模板文字生成的字符串,以排除通过以下 any/all JS 代码缩进创建的所有白色 space。

我使用正则表达式替换来去除第一个测试字符串中的前导 space。但是,如果字符串是 HTML,它有一个我想保留的缩进结构怎么办。

//problem: includes a lot of white space


    if(true){
        const aString = `This string
                        is multiline
                        and indented to match
                        the surrounding 
                        JS code`
        console.log(aString)
    }


//what I have tried

    if(true){
        const aString = `This string
                        is multiline
                        and indented to match
                        the surrounding 
                        JS code`
        
        const newString = aString.replace(/\n[ \t]+/g, " \n")
        console.log(newString)
    }
    
//but what about this

    if(true){
        const aString = `<div class="hello">
                            <div class="inner">
                               <span>Some text</span>
                            </div>
                         </div>`
        
        const newString = aString.replace(/\n[ \t]+/g, " \n")
        console.log(newString)
    }

我想打印:

<div class="hello">
   <div class="inner">
      <span>Some text</span>
   </div>
</div>

而不是:

<div class="hello">
<div class="inner">
<span>Some text</span>
</div>
</div>

common-tags 软件包有一个 stripIndent 标签可以为您完成这项工作。但是你需要在第二行开始这个字符串:

const aString = stripIndent`
                            <div class="hello">
                              <div class="inner">
                                <span>Some text</span>
                              </div>
                            </div>
`;

通常这是不可能用简单的正则表达式来完成的。你需要做的是统计每行前面的空格数,找出最小的空格数。然后完全删除这些。

一个简单的实现是这样的:

function removeIndent(str) {
  const lines = str.split('\n');
  if(lines[0] !== '' || lines[lines.length - 1] !== '') {
    return str;
  }
  lines.shift();
  lines.pop();
  
  const lens = lines.map(l => l.match(/ */)[0].length)
  const minLen = Math.min(...lens);
  return '\n' + lines.map(l => l.substr(minLen)).join('\n') + '\n';
}

const inStr = `
   foo
     bar
   baz
`;

const outStr = removeIndent(inStr);

console.log(inStr);
console.log(outStr);