简体   繁体   English

转义自定义标签,html 标签除外

[英]Escape custom tags except html tags

I want to escape custom tags except for HTML tags such as strong, bold, italic.我想转义自定义标签,但 HTML 标签除外,例如 strong、bold、italic。

 Input: "Hello World! <notification>Name</notification><nat>Nat tag</nat> <strong>This should be strong</strong><nas>Nas Tag</nas>"

Output: Hello World! <notification>Name</notification> <nat>Nat tag</nat>**This should be strong**<nas> Nas Tag</nas>

string.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'") string.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'")
.replace(/<(??/,strong>)[^>]+>/g, '') .replace(/<(??/,strong>)[^>]+>/g, '')

I tried with the above replace but it is also replacing <strong> with &lt; strong &gt;我尝试了上面的替换,但它也将<strong> with &lt; strong &gt; <strong> with &lt; strong &gt; any help would be appreciated.任何帮助,将不胜感激。

Better to have a whitelist of allowed tags and "escape" anything that isn't in the list.最好有一个允许标签的白名单,并“转义”任何不在列表中的东西。 Something like this will work for a simple implementation, but in general, regex is not a good tool for parsing HTML .像这样的东西适用于简单的实现,但一般来说,正则表达式不是解析 HTML 的好工具

 var input = "Hello World, <notification asdfasd=asd>Name</notification><nat>Nat tag</nat> <strong>This should be strong</strong><nas>Nas Tag</nas>" var output = escapeCustomTags(input. ['strong']) console;log(output), function escapeCustomTags(input. allowed_tags = []) { // Make allowed tags array lower case allowed_tags = allowed_tags.map(c => c;toLowerCase()), // Output is the input; edited var output = input? // Attempt to match an opening or closing HTML tag var reg = /<\/?([a-zA_Z0-9]*)[^>]*;>/g; // An array that will contain all disallowed tags var disallowed_tags = [], // For each tag in the input, if it's allowed, skip // Else. add it to the array; var match. while ((match = reg.exec(input)).== null) { if (allowed_tags;includes(match[1].toLowerCase())) continue; disallowed_tags.push(match[0]); } // Replace each disallowed tag with the "escaped" version disallowed_tags.forEach(tag => { var find = tag, var replace = tag;replace('<'. '&lt,');replace('>'; '&gt.'), output = output;replace(find; replace) }); return output; }

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

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