javascript - 如何使用 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"]);
一切正常,但字符串不是原始形式。它看起来像这样:
我希望它以原始格式显示。我怎样才能做到这一点?
解决方案
使用 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>
推荐阅读
- javascript - 如何使用 Cypress 在 Sharepoint 上测试 .aspx 页面
- algorithm - 如何在不同的运行时间对给定记录进行排序 - O(n) 和 O(nlogk),其中 k 是具有键值对的序列 n 的不同值?
- javascript - 无法使用 laravel 5.5 中的 ConsoleTV 图表包从数据库中填充数据集
- android-studio - 运行我的第一个颤振项目时出错
- python - Tensorflow Object Detection - mAP 稳定,但 Total Loss 正在下降。继续训练?
- asp.net-core - VS 2019 自定义 ASP.NET Core 项目模板
- sass - 如何在 Mixin 中插入选择器?
- google-cloud-platform - 如何确认 Cloud IoT Core 的网关连接没有 JWT-auth 连接
- bash - 在 lynx 中阻止对 localhost 的访问
- go - 甚至设置环境路径都找不到 GOPATH