如何处理模板文字中的多余空白

问题描述 投票:0回答:1

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

我使用了正则表达式替换来消除第一个测试字符串中的前导空格。但是,如果字符串是HTML,该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>
javascript regex template-literals
1个回答
1
投票

common-tags程序包具有为您执行此操作的common-tags标记。但是,您需要为此在第二行开始字符串:

stripIndent

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

一个简单的实现是这样:

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

© www.soinside.com 2019 - 2024. All rights reserved.