问题
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