1
votes

I have a text like this:

Sheldons Mutter Mary ist zu Besuch. Doch die Freude währt nicht lange: Statt von seiner Mutter ein Brathähnchen zubereitet zu bekommen, geht sie lieber auf Leonards Vorschlag ein, Sushi essen zu gehen. Sheldon hat zudem ein Unterhaltungsprogramm für Mary ausgearbeitet. Er muss aber schockiert zur Kenntnis nehmen, dass seine Mutter den Besuch eines Vortrags mit einem Nobelpreisträger ablehnt und stattdessen lieber mit den anderen eine Stadtrundfahrt macht.\n\nLeonard und Sheldon sind brillante Physiker, die meist in ihrem Apartment abhängen und ihre Videogames pflegen. Nur ihre Nachbarin Penny schafft es hin und wieder, für Abwechslung zu sorgen.

Now I want to replace \n\n with a <br />. So when I execute the line below, it doesn't do anything.

replace(/(\r\|\n|\r)/gm, "<br />");

However, it does work in the console.

4
Your plaintext has no newlines .. - Halcyon
@FritsvanCampen it does have \n\n - Naftali
the problem is your text does not have newlines, it has \n, that is "\\n" in Javascript. But \n in regex means newline. - Antti Haapala

4 Answers

3
votes

Since you seem to want to replace \n\n in a text like: foo\n\nbar - which to me sounds very strange by the way - you could do with this regexp:

var plain = "foo\\n\\nbar";
console.log(plain.replace(/\\n\\n/gm, "<br />"));
2
votes

Try this way:

var r = new RegExp("\n\n" , "g");
str = str.replace(r, "<br />");

JSFiddle: http://jsfiddle.net/bmMQN/4/

1
votes

Your code is missing 1 n

replace(/(\r\|\n|\r)/gm, "<br />");

should be

replace(/(\r\n|\n|\r)/gm, "<br />");

As it is now, it matches "\r|\n" OR "\r"

However, judging from the comments it indeed seems that your text does not have newlines but backslash characters and letters n (\n).

Thus the proper regex for them is

/(\\r\\n|\\n|\\r)/gm
0
votes

The line below will replace newlines with <br /> tags.

replace(/\r?\n/g, '<br />');