[英]How to replace content between html tags without replacing the tags themselves
假設我有一個像這樣的字符串:
<code>Blah blah Blah
enter code here</code>
<code class="lol">enter code here
fghfgh</code>
我想使用javascript用HTML對其進行編碼的回調函數替換<code>
標記之間的所有匹配項。
這是我目前擁有的:
function code_parsing(data){
//Dont escape & because we need that... in case we deliberately write them in
var escape_html = function(data, p1, p2, p3, p4) {
return p1.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
};
data = data.replace(/<code[^>]*>([\s\S]*?)<\/code>/gm, escape_html);
// \[start\](.*?)\[end\]
return data;
};
不幸的是,此功能是刪除"<code>"
標記並將其僅替換為內容。 我想將<code>
標記保留為任意數量的屬性。 如果僅將<code>
標記硬編碼回去,則會丟失屬性。
我知道regex不是最好的工具, 但是其中沒有嵌套的元素。
您不應該使用正則表達式來解析HTML。
就是說,您需要使用括號組捕獲要保留的內容,並將替換器附加到要操作的位上。
data.replace(/(<code[^>]*>)([\s\S]*?)(<\/code>)/g,
function (_, startTag, body, endTag) {
return startTag + escapeHtml(body) + endTag;
})
要了解為什么不應該使用正則表達式解析HTML,請考慮這樣做
<code title="Shows how to tell whether x > y">if (x > y) { ... }</code>
<code lang="js">node.style.color = "<code lang="css">#ff0000</code>"</code>
<code>foo</CODE >
<textarea><code>My HTML code goes here</code></textarea>
<code>foo <!-- commented out </code> --></code>
簡單的解決方案:在您的escape_html
函數中,在對字符串執行完操作之后,但是在返回字符串之前,請在字符串的前面附加和添加標簽,然后返回完整內容。
有時最簡單的答案是最好的:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.