目前我的应用程序像这样保存锻炼日志。
Start time: 8:49:41 PM Objective: 17 pushups a minute for 1 hour Total: 1020 pushups 59 minutes have gone by 0 pushups remaining 0 minutes remaining Times Paused: 0 Finished at: 9:49:41 PM
我正在尝试使用...来删除大量的空白和新行。
string.trim().replace(/[\s]/g," ").toString()
目标是保存文件,用新行删除大量空白,以便像这样轻松阅读......
Start time: 8:49:41 PM
Objective: 17 pushups a minute for 1 hour
Total: 1020 pushups
59 minutes have gone by
0 pushups remaining
0 minutes remaining
Times Paused: 0
Finished at: 9:49:41 PM
因此我的问题很简单。
如何用新行删除大量空白?
var string = output.textContent.toString();
console.log(string.trim().replace(/[\s]/g," ").toString())
<div id="output">
<h1>
Start time: 8:49:41 PM
</h1>
<h1>
Objective: 17 pushups a minute for 1 hour
</h1><br>
<h1>
Total: 1020 pushups
</h1>
<h1>
59 minutes have gone by
</h1>
<h1>
pushups remaining
</h1>
<h1>
0 minutes remaining
</h1>
<h1>
Times Paused: 0
</h1>
<h1>
Finished at: 9:49:41 PM
</h1>
</div>
问题已解决,感谢Emma's很棒的帮助...
string.trim().replace(/\s{2,}/gm,"\n").toString()
最佳答案
也许,\s{2,}
可能有效,如果不行,您可以尝试 \s{3,}
或 \s{4, }
被替换为新行:
const regex = /\s{2,}/gm;
const str = `Start time: 8:49:41 PM Objective: 17 pushups a minute for 1 hour Total: 1020 pushups 59 minutes have gone by 0 pushups remaining 0 minutes remaining Times Paused: 0 Finished at: 9:49:41 PM
`;
const subst = `\n`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log(result);
If you wish to explore/simplify/modify the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.
关于javascript - 用新行删除大量空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57815578/