Replacing more than two line breaks with regex

丶灬走出姿态 提交于 2019-12-06 08:59:23

问题


I want to search my textarea for "\n" line breaks but I want two line spaces to be the maximum.

What formula can I use in this regex so that it looks for anything over three \n's in a row ("\n\n\n") and replaces it with just one <br> ?

this.replace(new RegExp('\n', 'gim') , '<br/>');

回答1:


this.replace(new RegExp('(\n){3,}', 'gim') , '<br/>');

This will replace 3 or more \n's with a br, make that 4 if you want 4 or more.




回答2:


var newString = "some \n\n\n\n\n string".replace(/\n{3,}/g, '<br/>');

alert(newString);



回答3:


Did you try this?

this.replace(new RegExp('\\n+', 'gim') , '<br/>');

You can avoid using RegExp with:

this.replace(/\n+/g, '<br />')




回答4:


this.replace(/[\n]{3,}/g,'<br/>');


来源:https://stackoverflow.com/questions/8253792/replacing-more-than-two-line-breaks-with-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!