簡體   English   中英

轉義自定義標簽,html 標簽除外

[英]Escape custom tags except html tags

我想轉義自定義標簽,但 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, "'")
.replace(/<(??/,strong>)[^>]+>/g, '')

我嘗試了上面的替換,但它也將<strong> with &lt; strong &gt; <strong> with &lt; strong &gt; 任何幫助,將不勝感激。

最好有一個允許標簽的白名單,並“轉義”任何不在列表中的東西。 像這樣的東西適用於簡單的實現,但一般來說,正則表達式不是解析 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