首页 > 解决方案 > 如何处理模板文字中的多余空格

问题描述

您如何处理多行模板文字生成的字符串以排除通过遵循任何/所有 JS 代码缩进创建的所有空格。

我使用了正则表达式替换来消除我的第一个测试字符串中的前导空格。但是,如果字符串是具有我想保留的缩进结构的 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>

标签: javascriptregextemplate-literals

解决方案


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


推荐阅读