Javascript textarea aplanar cadena

var newString = someString.replace(/\n/, '#');

Works great, when i do an alert;


It appears as this:


I wish for it to display:


This is screwing up my other coding!

¿Alguien puede ayudarme?

preguntado el 02 de febrero de 12 a las 10:02

5 Respuestas

Some OS have \r\n for newlines. So, add an optional carriage return character to the RegExp. Also, add a global flag to your RegExp if you want to replace all occurrences:

var newString = someString.replace(/\r?\n/g, '#');

Respondido 02 Feb 12, 14:02

Intenta usar ...

var newString = someString.replace(/\n\r?/g, '#'))

Respondido 02 Feb 12, 14:02


someString.replace(/[\r\n]+/, '#');

Respondido 02 Feb 12, 14:02

Consecutive newlines will be replaced by a single #. - Rob W

Indeed, i'd assumed this was the desired behavior. - Sam Greenhalgh

If you are trying to prepend # to each line you might want this:

someString.replace(/^/gm, "#")


Respondido 02 Feb 12, 15:02

I would recommmend the following

function flatString(s) {
    // remove line separators (windows and linux) and trim multiple spaces
    s = s.replace(/\r\n/g, ' ')
        .replace(/\r/g, ' ')
        .replace(/\n/g, ' ')
        .replace(/[ ]+/g, ' ')

    return s;

You first delete the Windows line ends (\r\n are always together), then you remove the single characters (for linux line ends).

At this point, you flatted the string. However, depending on how many newline characters you had, you may end up with many spaces. So we try to convert all n-spaces to single spaces, and lastly do a trim so we get the shortest string as possible.

NOTE: this can be further optimized to try to run the most regex possibilities in a single execution, but it makes the cut at least.

Respondido 04 Oct 21, 05:10

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.