Remove multiple line breaks (\n) in JavaScript

前端 未结 2 858
深忆病人
深忆病人 2021-01-05 02:57

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

相关标签:
2条回答
  • 2021-01-05 02:57
    text = text.replace(/(\r\n|\r|\n){2,}/g, '$1\n');
    

    use this, it will remove newlines where there are at least 2 or more

    update

    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');
    
    0 讨论(0)
  • 2021-01-05 03:00

    We can tidy up the regex as follows:

    text = text.replace(/[\r\n]{2,}/g, "\n");
    
    0 讨论(0)
提交回复
热议问题