簡體   English   中英

正則表達式有助於替換 <html> 標簽

[英]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('&lt;(/)?(b|i|u)\\s*&gt;', 'gi'), '<$1$2>');

有人可以幫忙嗎?

我猜是像&lt;(/)?(b|i|u|code|pre)?( class="")\\\\s*&gt; ??

非常感謝

使用正則表達式解析html是一個壞主意,請參閱此答案

最簡單的方法是簡單地使用一些jQuery的dom操作函數來刪除格式化。

$('<div/>').find("b, i, code, code.lol").each(function() {
    $(this).replaceWith($(this).text());
});

關於jsfiddle的代碼示例。

這會將整個標記替換為其中的所有內容(包括class,id等):

.replace(new RegExp('&lt;(/)?(b|u|i|code|pre)(.*?)&gt;', 'gim'), '<$1$2$3>');

使用編碼字符串中的類來編寫代碼標記很難(可能是不可能的),當代碼標記采用固定格式( <code class="whatever"> )時很容易:

.replace(new RegExp('&lt;(?:(code\\sclass=".*?")|(/)?(b|u|i|code|pre)(?:.*?))&gt;', '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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM