Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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');
}
like image 815
Igor L. Avatar asked Jan 14 '23 01:01

Igor L.


2 Answers

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();
}
like image 121
Kaizen Programmer Avatar answered Jan 19 '23 10:01

Kaizen Programmer


Correct me if I'm wrong, but should it not be $.replaceAll() as it's a jQuery function not JS?

Or replace() in pure Javascript?

like image 38
Matt Fletcher Avatar answered Jan 19 '23 12:01

Matt Fletcher