在JavaScript中删除多个换行符(\ n) [英] Remove multiple line breaks (\n) in JavaScript
本文介绍了在JavaScript中删除多个换行符(\ n)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们为新员工提供了一份入职表格,其中需要删除多个换行符(每行之间4-5个).我想摆脱多余的换行符,但仍将空格与\ n隔开.
We have an onboarding form for new employees with multiple newlines (4-5 between lines) that need stripped. I want to get rid of the extra newlines but still space out the blocks with one \n.
示例:
New employee<br/>
John Doe
Employee Number<br/>
1234
我目前正在使用text = text.replace(/(\r\n|\r|\n)+/g, '$1');
,但是它消除了所有没有空格的换行符.
I'm currently using text = text.replace(/(\r\n|\r|\n)+/g, '$1');
but that gets rid of all newlines without spacing.
推荐答案
text = text.replace(/(\r\n|\r|\n){2,}/g, '$1\n');
使用此选项,它将删除至少有2个或更多的换行符.
use this, it will remove newlines where there are at least 2 or more
更新
根据OP的特定要求,我将对答案进行一点编辑.
on specific requirement of the OP I will edit the answer a bit.
text = text.replace(/(\r\n|\r|\n){2}/g, '$1').replace(/(\r\n|\r|\n){3,}/g, '$1\n');
这篇关于在JavaScript中删除多个换行符(\ n)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文