目前,我的应用程序像这样保存锻炼日志。
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()
答案 0 :(得分:2)
也许\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);
如果您想探索/简化/修改表达式,可以 在右上角的面板上进行了说明 regex101.com。如果您愿意, 也可以在this link中观看它的匹配方式 针对一些样本输入。
答案 1 :(得分:2)
没有疯狂的正则表达式。拆分,贴图,修剪和过滤器
var string = output.textContent.split(/\n+/).map(s => s.trim()).filter(s => s).join("\n")
console.log(string)
<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>
reg exp
var string = output.textContent.trim().replace(/\s*\n\s*/g, '\n').replace(/\n+/,'\n')
console.log(string)
<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>