首页 > 解决方案 > 如何使用 HTML 呈现原始字符串

问题描述

我想在 HTML 中呈现一个字符串,它的所有转义序列都完好无损:

像这样:

eipt 号 : 1995,\nmount 935\nAdm. : 17/06/2016\n\n说明 :\n\n4) 此卡仅在\n学生姓名和期间\n指定期间有效。\n\n2) 此卡不可转让,\n必须在任何时候\n需要时出示\n\n3) 万一丢失,\n这张卡的持有人必须立即书面告知\n委托人。\n\n4) \fanybody找到这张卡,他/她\n要求联系委托人。 \n\n \n\x0c

我从ajax请求接收这样的字符串,我正在设置一些标签的值,如下所示:

$('#ExtractedText').text(responce["text"]);

一切正常,但字符串不是原始形式。它看起来像这样:

在此处输入图像描述

我希望它以原始格式显示。我怎样才能做到这一点?

标签: javascripthtmlcss

解决方案


使用 PRE 格式化

const str = `Receipt No. : 1995,\nmount 935\nAdm. : 17/06/2016\n\nINSTRUCTIONS :\n\n4) This cards is valid only for\nstudent name & for the period\nindicated.\n\n2) This Card is not transferable and\nmust be produced whenever\ndemandes\n\n3) In case of its loss, the holder of\nthis card must intimate to the\nPrincipal immediately in writing.\n\n4) \fanybody finds this card, he/she\nis requested to reach the\nPrincipal.\n\n \n\x0c`
document.querySelector("pre").innerText=str;
<pre></pre>

不使用String.raw - 请参阅如何在 JavaScript 中转义反斜杠?

const str = String.raw`Receipt No. : 1995,\nmount 935\nAdm. : 17/06/2016\n\nINSTRUCTIONS :\n\n4) This cards is valid only for\nstudent name & for the period\nindicated.\n\n2) This Card is not transferable and\nmust be produced whenever\ndemandes\n\n3) In case of its loss, the holder of\nthis card must intimate to the\nPrincipal immediately in writing.\n\n4) \fanybody finds this card, he/she\nis requested to reach the\nPrincipal.\n\n \n\x0c`

document.getElementById("div1").innerText = str;
<div id="div1"></div>


推荐阅读