繁体   English   中英

如何仅编码此字符串的一部分并呈现html

[英]How to encode only part of this string and render html

我有一个字符串myString="<pre class='ql-syntax'><code><html><body>Will this work?</body></html></code></pre>" ,该字符串需要呈现在网页中,以便对<code>块中的内容进行编码,使其按原样显示。

$('<div/>').html(htmlString).html()删除htmlbody标签并输出以下内容:

<pre class="ql-syntax"><code>Will this work?</code></pre>

我想要的输出是:

<pre class="ql-syntax"><code>&lt;html&gt;hello&lt;/html&gt;</code></pre>

因此在网页上,代码块内的全部内容都会呈现出来。

如何仅编码myString在<code>块之间的部分?

我正在从数据库中获取myString,因此我对如何构造myString没有任何控制。 我可以操纵它,但是我想确保代码块内的html照原样呈现。

我建议你只想要

 <code><html><body>Will this work?</body></html></code>

被预知。 最好设置一个前置占位符。 比只是找到它并设置innerHtml。 例如这样的事情:

<pre class="ql-syntax" id="code"></pre>

var pre = document.getElementById("code");
var codeLength = '<code>'.length;
var start = htmlString.indexOf('<code>');
var stop = htmlString.indexOf('</code>');
if (start != -1 && stop != -1 && stop > start)
    pre.innerHtml = htmlString.substring(start+codeLength, stop-start-codeLength);

如果我理解您的问题,则需要对该字符串进行HTML编码,并包括<code>标记。 从输入字段读取属性时,请参阅HTML编码丢失

我不确定首先如何构造字符串,但是链接文章中的代码应该可以帮助您入门。 也许是这样的:

var newstring = "<pre class="ql-syntax">" + htmlEncode("<code><html><body>Will this work?</body></html></code>") + "</pre>";

这有帮助吗?

您可以将String.prototype.match()RegExp /(<pre?\\s.+?>)|(<code>)|[^\\1].+(?=<\\/code>)/g一起使用匹配"<pre"后跟空格字符,后跟一个或多个字符,后跟">""<code>"或者不匹配先前的捕获组"<code>"后跟一个或多个字符,后跟"</code>"

创建<div>元素和附加到document.body ,调用.shift()由返回的数组.match()得到"<pre>"中,设置div .innerHTML导致的.shift() ; 调用.shift()来获得"<code>"的比赛,设定为.innerHTMLdiv.firstChild<pre>调用.shift()设置结果作为.textContentdiv.firstChild.firstChild<code>

 var str = `<pre class="ql-syntax"><code><html><body>Will this work?</body></html></code></pre>`; var matches = str.match(/(<pre?\\s.+?>)|(<code>)|[^\\1].+(?=<\\/code>)/g); var div = document.createElement("div"); document.body.appendChild(div); var pre = matches.shift(); div.innerHTML = pre; var code = matches.shift(); div.firstChild.innerHTML = code; var html = matches.shift(); div.firstChild.firstChild.textContent = html; 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM