Replace <br /> in a textarea with a line separator ( Javascript )

Igor L. picture Igor L. · Mar 5, 2013 · Viewed 17.1k times · Source

I guess this will be answered in two minutes but I am not able to google out a solution.

Tried: this, this

I have a textarea which first recieves some data from the server (dynamically using AJAX). The text in the textarea may look like this:

Hello&nbsp;Cruel&nbsp;<br&nbsp;/>World!

My users do not like the look of this :)

So I wrote a very simple function:

    function replaceHtml( string_to_replace ) 
    {
        var result = replaceAll( string_to_replace, "&nbsp;", " ");
        result = result.replace(/<br\s*\/?>/mg,"\n\r"); // or "\n", "\r", "\r\n"
        return result;
     }

My output looks like this:

Hello Cruel World!

Instead of:

Hello Cruel
World!

I would love a solution that is at most 5 lines long and can be applied with all browsers and OSes

Btw, Im no fan of regexes, so maybe the real problem will be there..

UPDATE

From this answer and mr Michael_B I got this solution, which is working for me, but I've got a hunch the character might not be the best solution there is:

function replaceHtml( string_to_replace ) 
{
    return string_to_replace.replace(/&nbsp;/g, ' ').replace(/<br.*?>/g, '\u2028');
}

Answer

Kaizen Programmer picture Kaizen Programmer · Mar 5, 2013

Based on @Explosion Pills comment and jsFiddle

DEMO

function replaceHtml( string_to_replace ) 
{
        return string_to_replace.replace(/&nbsp;/g, ' ').replace(/<br.*?>/g, '\n');
}

UPDATE based on New line in text area

Updated DEMO

Maybe this will fix your issue with \n - Requires jQuery.

function replaceHtml(string_to_replace) {
    return $("<div>").append(string_to_replace.replace(/&nbsp;/g, ' ').replace(/<br.*?>/g, '&#13;&#10;')).text();
}