23

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);
    }
});
eugeneK
  • 10,750
  • 19
  • 66
  • 101
  • 6
    usually it's not a good idea to replace it on the client side – Teneff Jun 13 '11 at 14:40
  • @Teneff, \n is not sent then to the server, it seems omitted. I can change it on server but i receive nothing except of text. – eugeneK Jun 13 '11 at 14:42
  • 1
    You should also store it in the raw format entered, if you ever added a new app to retrieve data that could support the /n then surely you should show it? have you tried encoding it? – jimplode Jun 13 '11 at 14:43
  • is `#input` an ``? Because if it is you will not get any `\n`. If it is a textarea I suggest you convert the data when the user clicks the button to submit and not when typing. But better than that I would just convert on the server-side. – BrunoLM Jun 13 '11 at 15:18
  • @BrunoLM, #input is textarea and i do replace \n to :br: at submit and turn :br: to br html tag when i get data back from server. Why i'm not doing it on server because besides br tags i have images and image tag is quite long one to send via service to jQuery wrapper so i mark tags i need with colons, alike forums do that with [tagname] – eugeneK Jun 13 '11 at 17:51

11 Answers11

39

Replace with global scope

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

or

$('#input').val().replace("\n", "<br />", "g")
BrunoLM
  • 97,872
  • 84
  • 296
  • 452
12

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

Teneff
  • 30,564
  • 13
  • 72
  • 103
  • Doesn't work since he wants to replace `\n` and not `/\n/`. And if it was intended to be a regex it would only replace the first occurrence. – BrunoLM Jun 13 '11 at 14:45
  • @Qtax, it replaces just first appearance of \n and omits others – eugeneK Jun 13 '11 at 14:47
  • 1
    Just use a string replacement, like `"\n"`, if you really want to use regex you can do `/\n/g`. – Qtax Jun 13 '11 at 14:48
7

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.

rzetterberg
  • 10,146
  • 4
  • 44
  • 54
2

If you support PHP you should check this out: http://php.net/manual/en/function.nl2br.php

Allman
  • 41
  • 4
2

You can use a simple javascript string function.

 string.replace("\n", "<br>")
Wicked Coder
  • 1,128
  • 6
  • 8
2

you can use javascript built in replace function with a little help of regex, for example

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

this code will return all enters replaced with <br>

Senad Meškin
  • 13,597
  • 4
  • 37
  • 55
  • This is the only one out of this entire page that worked for me for wordpress editor. If you are using a wordpress editor in a plugin, and need to for some reason show a preview of the editors contents, this is the only one here that works. – David Lawrence Nov 26 '13 at 03:03
  • Did you really tried every solution from this question, if you did then you are really persistent. :) – Senad Meškin Nov 27 '13 at 13:46
1

The following will replace all instances of \n with a <br /> :

while (message.indexOf("\\n") !== -1) {
   message = message.replace("\\n", "<br />");
}
parliament
  • 21,544
  • 38
  • 148
  • 238
1

From within your WCF service can you not just use String.Replace ?

text = text.Replace("\n","<br />");
Richard Friend
  • 15,800
  • 1
  • 42
  • 60
  • Don't do this! You've to use a regular expression to replace all matches globally. E.g, in your case, it will only replace the first occurrence – Karue Benson Karue Apr 03 '20 at 23:44
1
var replaced = $('#input').val().replace("\n", "<br/>");
Qtax
  • 33,241
  • 9
  • 83
  • 121
1

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:

function nl2br (str, is_xhtml) {
    // Converts newlines to HTML line breaks  
    // 
    // version: 1103.1210
    // discuss at: http://phpjs.org/functions/nl2br    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Philip Peterson
    // +   improved by: Onno Marsman
    // +   improved by: Atli Þór
    // +   bugfixed by: Onno Marsman    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Maximusya
    // *     example 1: nl2br('Kevin\nvan\nZonneveld');    // *     returns 1: 'Kevin\nvan\nZonneveld'
    // *     example 2: nl2br("\nOne\nTwo\n\nThree\n", false);
    // *     returns 2: '<br>\nOne<br>\nTwo<br>\n<br>\nThree<br>\n'
    // *     example 3: nl2br("\nOne\nTwo\n\nThree\n", true);
    // *     returns 3: '\nOne\nTwo\n\nThree\n'    var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '' : '<br>';

    return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}

http://phpjs.org/functions/nl2br:480

Tomas Reimers
  • 3,234
  • 4
  • 24
  • 37
  • What $1 and $2 mean? ([^>\r\n]?) and (\r\n|\n\r|\r|\n) – eugeneK Jun 13 '11 at 15:03
  • To tell you the Truth, I am not so good with regex as I should be. But the little I do know about this is summed up in these two links: Dollar Signs - http://mootools-users.660466.n2.nabble.com/Moo-preg-replace-in-javascript-td4718179.html; all the r's and n's - http://lawrence.ecorp.net/inet/samples/regexp-format.php (scroll down to the section about replacing carriage returns with html br. And the code works as shown here - http://jsfiddle.net/Dar96/9/ – Tomas Reimers Jun 13 '11 at 15:32
0

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:

text = text.Replace(/\\n/g,"<br />");
fred
  • 1,146
  • 11
  • 16