简体   繁体   English

RegEx如何避免自动关闭HTML标签

[英]RegEx How to avoid automatically closing HTML tags

HTML: HTML:

<pre class="html">
   List<String> list = Arrays.asList(str);
</pre>

JS: JS:

var symbols = /(<|>|{|})/gi;

$('.html').each(function() {
   var abc =  $(this).html().replace(symbols, "<span class='blue'>$1</span>");
$(this).html(abc);
}

Output: (I am able to change the color of <,>) 输出:(我可以更改<,>的颜色)

List<string> list = Arrays.asList(str);
</string>

Its automatically appending 它自动附加

 </string> at the end

and changing String to string (First letter capital to small) 并将“字符串”更改为“字符串”(首字母大写改为小写)

Can anybody please help me how to fix this issue. 谁能帮我解决此问题。

Don't do this: 不要这样做:

<pre class="html">
   List<String> list = Arrays.asList(str);
</pre>

Escape your brackets: 逃脱括号:

<pre class="html">
   List&lt;String&gt; list = Arrays.asList(str);
</pre>

An alternative way would be to put your code in a script tag to avoid it being interpreted as an HTML tag: 另一种方法是将代码放在脚本标签中,以避免将其解释为HTML标签:

<script type="template" id="code">
List<String> list = Arrays.asList(str);
</script>
<div id="output"></div>

var symbols = /(<|>|{|})/gi;

var code = document.getElementById("code").textContent;
document.getElementById("output").innerHTML = code.replace(symbols, "<span class='blue'>$1</span>");

The downside is that all your leading whitespaces would be gone. 缺点是您所有领先的空格都将消失。

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

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