Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace \n with <br /> in JavaScript?

Tags:

I have a textarea where I insert \n when user presses enter. Code from this textarea is sent to a WCF service via jQuery.ajax(). I cannot save \n in DB as it won't show in other applications consuming the service.

How can i replace \n with <br /> tag?

solution

Well many of you tried and some got right with Javascript Regex with /g (global modifier). At the end i had \n inserted twice, i don't know why, my only guess is that jQuery on keypress event created double \n which i debug.

$('#input').keypress(function (event) {
    if (event.which == '13') {
        inputText = $('#input').val() + '\n';
        $('#input').val(inputText);
    }
});
like image 648
eugeneK Avatar asked Jun 13 '11 14:06

eugeneK


People also ask

How do I replace all line breaks in a string with br /> elements?

The RegEx is used with the replace() method to replace all the line breaks in string with <br>. The pattern /(\r\n|\r|\n)/ checks for line breaks. The pattern /g checks across all the string occurrences.

How do you replace a line break in a string?

In order to replace all line breaks from strings replace() function can be used.

Can I use Br in JavaScript?

To create a line break in JavaScript, use “<br>”. With this, we can add more than one line break also.

What does \n mean in JS?

The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.


3 Answers

Replace with global scope

$('#input').val().replace(/\n/g, "<br />") 

or

$('#input').val().replace("\n", "<br />", "g") 
like image 195
BrunoLM Avatar answered Oct 14 '22 21:10

BrunoLM


it could be done like this:

$('textarea').val().replace(/\n/g, "<br />");

edit: sorry ... the regular expressions in javascript should not be quoted

working example

like image 33
Teneff Avatar answered Oct 14 '22 21:10

Teneff


Like said in comments and other answer, it's better to do it on server side.

However if you want to know how to do it on clientside this is one easy fix:

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

Where textareaContent is the variable with the data in the textarea.

Edit: Changed so that it replaces globally and not only first match.

like image 31
rzetterberg Avatar answered Oct 14 '22 19:10

rzetterberg