简体   繁体   English

转义小于和大于 HTML

[英]Escape less than and greater than in HTML

content = '5<x<div></div>'

Basically I am looking for a regular expression that will make the string like above into 5&lt;x<div></div>基本上我正在寻找一个正则表达式,它将使上面的字符串变成5&lt;x<div></div>

5x<div></div> will still be 5x<div></div> . 5x<div></div>仍然是5x<div></div> I am just trying to escape unclosed html tags我只是想逃避未封闭的 html 标签

If there is such a library then I will be very happy to use it as long as it meets my main goal of trying to escape unclosed html tags如果有这样的库,那么我会很乐意使用它,只要它符合我试图逃避未封闭 html 标签的主要目标

  1. Rewrite each open tag character "<" with the symbol + unique value... in this case ",,#*&,,"用符号 + 唯一值重写每个打开的标记字符“<”...在这种情况下为“,,#*&,,”
  2. Split the string at the unique value以唯一值拆分字符串
  3. The "replaceString ()" function checks if the passed value is really a tag... whether both "<" and ">" characters are present in the string. “replaceString ()” function 检查传递的值是否真的是一个标签……字符串中是否同时存在“<”和“>”字符。 If not present, rewrite the character with "& lt;".如果不存在,则用“& lt;”重写该字符。
  4. The whole process is repeated for the symbol ">"对符号“>”重复整个过程

This is not the most beautiful solution to this task but it works.这不是这个任务最漂亮的解决方案,但它确实有效。

 var str = '5<x<div>s>7</div>'; for (var i = 0; i < 2; i++) { if (i === 0) { var str2 = str.replace(/</gi, ",,#*&,,<"); var spl = str2.split(",,#*&,,"); } else { var str2 = str.replace(/>/gi, ">,,#*&,,"); var spl = str2.split(",,#*&,,"); } replaceString(spl); } function replaceString(spl) { for (let i = 0; i < spl.length; i++) { if (spl[i].indexOf('<') > -1 && spl[i].indexOf('>') > -1) { //....... } else { if (spl[i].indexOf('<') > -1) { spl[i] = spl[i].replace(/</gi, "&lt;"); } else if (spl[i].indexOf('>') > -1) { spl[i] = spl[i].replace(/>/gi, "&gt;"); } } } str = spl.join(''); } console.log(str);

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

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