[英]regex help with replacing <html> tags
我需要擴展下面的正則表達式,以便它也選擇帶有類的<code>標簽,例如<code class =“lol”>
var text = 'This is <i>encoded text</i> but this is <b>bold</b >!';
var html = $('<div/>')
.text(text)
.html()
.replace(new RegExp('<(/)?(b|i|u)\\s*>', 'gi'), '<$1$2>');
有人可以幫忙嗎?
我猜是像<(/)?(b|i|u|code|pre)?( class="")\\\\s*>
??
非常感謝
這會將整個標記替換為其中的所有內容(包括class,id等):
.replace(new RegExp('<(/)?(b|u|i|code|pre)(.*?)>', 'gim'), '<$1$2$3>');
使用編碼字符串中的類來編寫代碼標記很難(可能是不可能的),當代碼標記采用固定格式( <code class="whatever">
)時很容易:
.replace(new RegExp('<(?:(code\\sclass=".*?")|(/)?(b|u|i|code|pre)(?:.*?))>', 'gim'), '<$1$2$3>');
我不會使用正則表達式來解析標記,但如果它只是一個字符串片段,這樣的東西就足夠了。 應該注意的是,你使用的正則表達式使用\\ s *負擔過重。 它的可選形式可以通過開銷來替換完全相同的東西。 最好使用\\ s +
正則表達式: <(/?(?:b|i|u)|code\\s[^>]+class\\s*=\\s*(['"]).*?\\2[^>]*?)\\s+>
替換: <$1>
修飾符: sgi
< # < Opening markup char
( # Capture group 1
/? # optional element termination
(?: # grouping, non-capture
b|i|u # elements 'b', 'i', or 'u'
) # end grouping
| # OR,
code # element 'code' only
\s [^>]* # followed by a space and possibly any chars except '>'
class \s* = \s* # 'class' attribute '=' something
(['"]) .*? \2 # value delimeter, then some possible chars, then delimeter
[^>]*? # followed by possibly any chars not '>'
) # End capture group 1
\s+ # Here need 1 or more whitespace, what is being removed
> # > Closing markup char
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.