简体   繁体   English

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

[英]how to deal with extraneous white-space in template literals

How do you process a multi-line template-literal generated string to exclude all the white space that is created by following any/all JS code indentation.您如何处理多行模板文字生成的字符串以排除通过遵循任何/所有 JS 代码缩进创建的所有空格。

I have used a regex replace to get rid of leading space in my first test string.我使用了正则表达式替换来消除我的第一个测试字符串中的前导空格。 But what if the string is HTML which has an indentation structure that I would like to preserve.但是,如果字符串是 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) }

I would like it to print:我希望它打印:

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

and not:并不是:

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

The common-tags package has a stripIndent tag that does this for you. common-tags package 有一个stripIndent标签可以为你做这件事。 However you need to start the string on the second line for this:但是,您需要为此在第二行开始字符串:

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

generally this is not possible to do with a simple regex.通常,这不可能用简单的正则表达式来完成。 What you need to do is to count the number of spaces in front of each line and figure out the smallest number of spaces.您需要做的是计算每行前面的空格数并找出最小的空格数。 Then remove exactly these.然后完全删除这些。

A simple implementation is this:一个简单的实现是这样的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM