首页  >  问答  >  正文

如何自动替换预定义的标签

<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 天前466

全部回复(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
  • 取消回复