Skip to content Skip to sidebar Skip to footer

Replace Linebreaks To Get Them Working With Jquery

I have following small script to preview some text before submitting it to store in a database: jQuery(function($) { var input = $('#contents'), preview = $('#previewaccord

Solution 1:

I assume that you are using a textarea for the input. There are \n used as linebreaks, which have no influence in HTML. So you have to replace them with br-tags:

input.val().replace(/\n/g, "<br />");

Solution 2:

It's nothing to do with jQuery: Linebreaks in HTML are not significant, they're just whitespace (like spaces and tabs).

To force a linebreak in HTML, you use a <br> tag. So you could change

preview.html(input.val());

to

preview.html(input.val().replace(/\r?\n/g, '<br>'));

Note that you're also not escaping HTML special characters (like < or &), and so if you type them, your output may not be correct. So you might go with:

preview.html(input.val().replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/\r?\n/g, '<br>'));

And finally, I'd hook keypress as well as keyup, so you see characters created via key repeat (which fires keypress, but not keyup).

Live example | source

Solution 3:

Hiya demo here:http://jsfiddle.net/STnhV/1/

hope this helps! cheers!

Jquery Code:

$(document).ready(function() {
    $('#inputfoo').keyup(function() {
       $('#outputbar').html($(this).val().replace(/\n/g,'<br/>')); 
    });
});

​

Solution 4:

Replace the linebreaks to html break tags when you render the output from the database.

Post a Comment for "Replace Linebreaks To Get Them Working With Jquery"