[英]how to get js to render newlines in rendered content using innerHTML
Fiddle here - http://jsfiddle.net/kQ3eJ/3/ 在这里提琴-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 基本上,网页上有一个元素,其innerHTML中包含换行符(来自JSON的数据),我想格式化此数据,以便在前端更清晰易读
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. 正如您在小提琴中看到的那样-在JavaScript工作中输入换行符(\\ n),但是如果换行符是来自innerHTML的字符串的一部分,则不会正确设置其格式。
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 好的,所以我尝试将字符串“ \\ n”替换为“ \\ n”,将“ \\ r”替换为“ \\ r”,这似乎起作用了
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? 但这在unicode替换上失败-我可能必须将整个unicode块替换为一个?
实际上,它看起来像JSON.parse()将取消所有\\ n \\ r和\\ u的转义,并允许其在<pre></pre>
标记中正确格式化
document.getElementById("foo").innerHTML = '<pre>' + JSON.parse('"' + htmlString + '"') + '</pre>';
There is no need to use JSON.parse
for this. 无需为此使用
JSON.parse
。 By default Javascript
will consider the \\n
as new line. 默认情况下,
Javascript
会将\\n
视为新行。
Refer the following question. 请参考以下问题。
JavaScript string with new line - but not using \\n 带换行符的JavaScript字符串-但不使用\\ n
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.