0

Fiddle here - http://jsfiddle.net/kQ3eJ/3/

var string = "This is a & string that has \n new lines in it\u0027s body";

//does not do the newline or unicode
document.getElementById("insertJavascript").innerHTML = string;

//does do the newline and unicode
document.getElementById("insertJavascriptWithPre").innerHTML = '<pre>' + string + '</pre>'; 

//but if i get the string from the HTML to begin with it doesn't work
var htmlString = document.getElementById("htmlWithNewline").textContent;
document.getElementById("insertJsHtmlWithNewline").textContent = htmlString; 

basically the webpage has a element whose innerHTML has newlines in it (data from a JSON) I want to format this data so it's more legible on the front end

As you can see in the fiddle - typing the newlines (\n) into javascript work, but if the newline is a part of a string that comes from the innerHTML, it does not get formatted correctly.

Is there a way to "unescape" the newlines in the string?

Okay so I tried to string replace the "\n" with "\n" and "\r" with "\r" and that seems to have worked

var what = htmlString.replace('\\n','\n');
// what = what.replace('\\u','\u');
what = what.replace('\\r','\r');
document.getElementById("a").innerHTML = '<pre>' + what + '</pre>'; 

but it's failing on the unicode replace - I may have to replace the entire unicode block as one?

wyu
  • 1,793
  • 17
  • 33

2 Answers2

0

Actually it looks like JSON.parse() will unescape all the \n \r and \u and allow it to be formatted correctly in the <pre></pre> tags

document.getElementById("foo").innerHTML = '<pre>' + JSON.parse('"' + htmlString + '"') + '</pre>';
wyu
  • 1,793
  • 17
  • 33
0

There is no need to use JSON.parse for this. By default Javascript will consider the \n as new line.

Refer the following question.

JavaScript string with new line - but not using \n

Community
  • 1
  • 1
Madhu
  • 2,416
  • 3
  • 15
  • 33
  • Did you get a chance to look at the fiddle? JS treats JS strings as newlines but if the string is pulled from a webpage via innerHTML it recognizes the newline as an escaped newline (literal \n) – wyu Apr 11 '14 at 16:28