[英]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()
删除html
和body
标签并输出以下内容:
<pre class="ql-syntax"><code>Will this work?</code></pre>
我想要的输出是:
<pre class="ql-syntax"><code><html>hello</html></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>"
的比赛,设定为.innerHTML
的div.firstChild
: <pre>
调用.shift()
设置结果作为.textContent
的div.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.