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);
}
});
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.
In order to replace all line breaks from strings replace() function can be used.
To create a line break in JavaScript, use “<br>”. With this, we can add more than one line break also.
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.
Replace with global scope
$('#input').val().replace(/\n/g, "<br />")
or
$('#input').val().replace("\n", "<br />", "g")
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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With