javascript - 如何处理模板文字中的多余空格
问题描述
您如何处理多行模板文字生成的字符串以排除通过遵循任何/所有 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>
解决方案
该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);
推荐阅读
- unity3d - 无法与 Unity 包管理器本地服务器进程建立连接 - Unity?
- facebook-graph-api - FB Graph API:FB 帖子(处于公开状态)不向粉丝用户显示
- java - 无法使用 Mockito 模拟 accountStatus
- java - java中的扩展私有字段
- django - 运行应用程序时弹出 /test/ 处的 TemplateDoesNotExist 错误
- python - 使用 pip 在 windows 中安装模块 kivy 失败
- c++ - 难以理解使用 BIT 计算反转次数的代码
- javascript - React – 从对象中的数组创建数组
- typescript - 打字稿:将属性连接到字符串文字类型?
- android - 一个视图内的多个回收视图(gridlayout 和水平线性布局)