2017-07-26 205 views
-4

我想在JavaScript中創建一個正則表達式。我想要做的:Javascript的正則表達式:替換字符串中的實例

  1. 我想看看是否有一個html元素class=「get-me」字符串中的任何地方。
  2. 如果有我想用I found you替換它。

實例:

  1. <div class="get-me" />

結果:I found you

  • <div>Some text <div class="get-me" data-type="data-type" js="js" /> more things happening here</div>
  • 結果:<div>Some text I found you more things happening here</div>

  • <div>Some text <p class="get-me" /> more things</div>
  • 結果:<div>Some text I found you more things</div>

  • I m testing <<<<div class="get-me" />
  • 結果:I m testing <<<I found you

    謝謝。

    +8

    [不解析與正則表達式HTML](https://stackoverflow.com/a/1732454/3001761) – jonrsharpe

    +0

    爲什麼你認爲我想解析HTML?我有一個不解析的特定用例。 – zsid

    +1

    在html標籤中查找一個類是_parsing_。爲此,您可以使用[sizzlejs](// sizzlejs.com)等庫,而不是使用正則表達式。也沒有JavaScript的後代,但[有替代品](https://stackoverflow.com/q/7376238/6320039) –

    回答

    1

    沒有進入解析HTML辯論,這將回答你原來的(未經編輯的)問題:

    const replacementText = 'I found you'; 
    const regex = /(.*)<\w+\s.*class="get-me".*\/>(.*)/; 
    let str = '<div>Some text <div class="get-me" data-type="data-type" js="js" /> more things happening here</div>'; 
    str = str.replace(regex, `$1${replacementText}$2`); 
    

    輸出是

    "<div>Some text I found you more things happening here</div>" 
    

    這裏是你JSBin:https://jsbin.com/rowaxayodu/edit?js,console

    1

    這個工程,發現任何標籤class="getMe"在裏面。
    然後您可以將其替換爲空(將其從文本中刪除)。

    請注意,如果不匹配所有標籤,您無法真正匹配特定標籤。
    這是因爲標記可以嵌入其他標記的,等...

    /<[\w:]+(?=(?:[^>"']|"[^"]*"|'[^']*')*?\sclass\s*=\s*(?:(['"])\s*getMe\s*\1))\s+(?:"[\S\s]*?"|'[\S\s]*?'|[^>]*?)+>/

    https://regex101.com/r/PHUrIi/1

    擴展

    < [\w:]+    # Any tag 
    
    (?=     # Assert (a pseudo atomic group) 
         (?: [^>"'] | " [^"]* " | ' [^']* ')*? 
         \s class \s* = \s* 
         (?: 
          (['"])    # (1), Quote 
          \s* getMe \s*   # With 'class="getMe" 
          \1 
        ) 
    ) 
    \s+ 
    (?: " [\S\s]*? " | ' [\S\s]*? ' | [^>]*?)+ 
    > 
    
    相關問題