DEV Community

Georgia Lumley
Georgia Lumley

Posted on

Add in line breaks into a string [closed]

Add in line breaks into a string

-4

I am being given a string from an API that contains \n in it.

For example: "Hello there.\n How are you?\n"

I need to remove the \n (as there currently have no effect in the string) and replace them with the intended line break.

This will produce:

"Hello there. 
 How
…

Top comments (1)

Collapse
 
moopet profile image
Ben Sinclair • Edited

It's unclear what you're asking because:

  • Javascript is often used in a browser. Line breaks in HTML are different to line breaks in the console. Which is it? Adding tags for node or mentioning in the question would help.
  • \n in a double-quoted string is already a line break, and for it to appear as in the question, it's probably escaped as \\n or something, but we can't tell from the way the question is phrased
  • The tags and question talk about regex, but that's not the approach most people would take, so people will be reluctant to write an answer that might miss the point of the question. It's a bit tricky to get regex to do what you want in Javascript sometimes, especially if you're new to it and it uses multi-line strings.
  • It's not clear what you mean by /n (with the forward slash. You start by saying you'd like line breaks, and then end up by giving an example with /n in it, which doesn't have any special meaning.
  • Line breaks are different on different OSs, for instance on Windows it might not work until you get \r\n instead. I can't remember the ins and outs of this right now though.

To directly answer, using String.replace is probably what you want:

let str = "Hello there.\\n How are you?\\n";
let fixedStr = str.replace("\\n", "\n");

console.log(str)
console.log(fixedStr);

Given we're not sure what you're going for though, you could try out a bunch of variations like these:

console.log(str.replace("\n", "/n"));
console.log(str.replace("\\n", "/n"));
console.log(str.replace("\\n", "\n"));
console.log(str.replace("\n", "<br>"));
console.log(str.replace("\\n", "<br>"));

Until you get whatever you're after

If you edit the question on SO, even though it's closed, it'll get put in the queue to get reviewed for re-opening.