简体   繁体   中英

RegEx How to avoid automatically closing HTML tags

HTML:

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

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:

<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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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