首頁  >  問答  >  主體

如何自動替換預先定義的標籤

<p>我有一些字元需要如上所述替換,但我不知道如何替換:</p><p> 要替換的字元:</p> <pre class="brush:php;toolbar:false;">first | end | <day> | | <red> | </red>| <a ###> | </> |</pre> <p><code>day => 取得目前日期(例如:14)</code></p><p> <code>紅色 => 顏色紅色</code> </p><p> <code><a ###https://www.google.com/>連結</> => <a href="https://www.google.com/">連結</></code></p> <p><code>輸入:你好<red>Siro先生</red></code> </p><p> <code>輸出:你好<span style="color: red">Siro先生</span></code></p> <p>我的聊天記錄。 </p> <p>可以告訴我如何寫一個通用函數來檢查上述標籤的替換嗎? 這是我的程式碼:</p> <p> <pre class="snippet-code-js lang-js prettyprint-override"><code>export const formatTags = (content) => { const firstTag = "<red>"; const secondTag = "</red>"; const tagsIndex = [...content.matchAll(new RegExp(firstTag, "gi"))].map( (a) => a.index ); const initialContent = content; tagsIndex.forEach((index) => { const tagContent = initialContent.substring( index firstTag.length, initialContent.indexOf(secondTag, index) ); if (firstTag === "<red>") { content = content.replaceAll( `${firstTag}${tagContent}${secondTag}`, `<span style="color: red">${tagContent || "わからない"}</span>` ); } }); return content; };</code></pre> </p> <p> <pre class="snippet-code-html lang-html prettyprint-override"><code><span :class="(msg.image || msg.file) && msg.text ? 'mt-2' : ''" v-html="msg.text" v-linkified:options="{ className: currentUserId === msg.senderId ? 'message-external-link' : '', }" /></code></pre> </p> <p>抱歉我的英文不太好! </p><p> 謝謝大家! </p>
P粉330232096P粉330232096388 天前467

全部回覆(1)我來回復

  • P粉388945432

    P粉3889454322023-09-04 09:34:29

    您可以建立替換規則的Map。用於捕獲文字的正規表示式將是鍵,replace 中使用的替換函數回呼將是值。循環遍歷規則並更新字串。

    const input = `Today is <day>th day of the month. 
    I'd like <red> this text to be in red</red> 
    and <blue>this to be in blue</blue>. 
    Testing the links <a ###https://www.google.com/>with Google</>
    and <a ###https://stackoverflow.com/>Stak Overflow</>`
    
    function convert(str) {
      const replacerRules = new Map([
        [/<day>/g, new Date().getDate()],
        [/<([^>]+)>([^<]+)<\/>/g, (_, p1, p2) => `<span style="color: ${p1}">${p2}</span>`],
        [/<a #+([^>]+)>([^<]+)<\/>/g, (_, p1,p2) => `<a href="${p1}">${p2}</a>`]
      ])
      
      for (const [key, replacer] of replacerRules)
        str = str.replace(key, replacer)
      
      return str
    }
    
    console.log( convert(input) )
    document.querySelector("div").innerHTML = convert(input)
    <div />

    回覆
    0
  • 取消回覆