What I am looking to do is allow 2 line breaks for formatting, but preventing 3 or more from displaying (in preview before submit, so cant just strip it out with php)
I started with
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n){2,}/g, '$1'+ breakTag +'$2');
I tried adding {2,}
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n){2,}/g, '$1'+ breakTag +'$2');
provided in <textarea>
this is user input
i have inserted 1 line break
i have inserted 3 line breaks
i have inserted 4 line breaks
what I want is
this is user input
i have inserted 1 line break
i have inserted 3 line breaks
i have inserted 4 line breaks
what I am getting is
this is user inputi have inserted 1 line break
i have inserted 3 line breaks
i have inserted 4 line breaks
without the {2,} it displays as input
bonus if we can keep them from entering more than 2 line breaks consecutively in the textarea to begin with, as well as clean it up on preview
* edit *
$('textarea').keyup(function()
{
var myString = $(this).val();
myString = nl2br(myString);
$('#preview').html(myString);
});
function nl2br (str, is_xhtml)
{
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
}
Here is code to replace both the value in the textarea and insert <br />
into a div. This isn't in the context of jQuery, but you don't have to use it for something like this. It should be straightforward to convert to jQuery, though.
Edit: avoid error if the textarea is empty.
<script>
function oneBreak(ta) {
outDiv = document.getElementById('outDiv');
if (ta.value.length <= 0) {
outDiv.innerHTML = '';
} else {
var val = ta.value + "";
var ln = "\n";
//normalize line breaks
if (val.match(/(\r\n)/g)) ln = "\r\n";
else if (val.match(/\r/g)) ln = "\r";
val = val.replace(/(\r\n)/g,"\n");
val = val.replace(/\r/g,"\n");
val = val.replace(/(\s*\n{3,})+/g,"\n\n")
// return to default line breaks
ta.value = val.replace(/\n/g,ln);
outDiv.innerHTML = val.replace(/\n/g, "<br />");
}
return outDiv.innerHTML;
}
</script>
<textarea id="breaks" onKeyUp="oneBreak(this);" onChange="oneBreak(this);"></textarea>
<div id="outDiv"></div>
Edit 2: add space-only line removal. JS Fiddle: http://jsfiddle.net/2T2gv/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.