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);
}
});
it could be done like this:
edit: sorry … the regular expressions in javascript should not be quoted
working example
From within your WCF service can you not just use
String.Replace
?If you support PHP you should check this out: http://php.net/manual/en/function.nl2br.php
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:
Where
textareaContent
is the variable with the data in the textarea.Edit: Changed so that it replaces globally and not only first match.
You can use a simple javascript string function.
Replace with global scope
or
you can use javascript built in replace function with a little help of regex, for example
this code will return all enters replaced with
<br>
Building on the other answers, this is probably done best by php. Now assuming you don’t want to ajax this (which would be pointless and cause unnecessary server load), you should probably use phpjs.org‘s javascript port of this function:
http://phpjs.org/functions/nl2br:480
I know this is an ancient question/answer but it’s one of the first to come up on a google search and no longer works here in the distant future with current browsers.
The correct answer to convert the
\n
to<br />
(at least for me) is:The following will replace all instances of
\n
with a<br />
:Tmauqr – 4 propecia Nkkhgd asifhr
Rhuiim – buy sildenafil citrate tablets 100mg Cpbuey tfklze