Heim  >  Fragen und Antworten  >  Hauptteil

So ersetzen Sie vordefinierte Tags automatisch

<p>Ich habe einige Zeichen, die wie oben beschrieben ersetzt werden müssen, weiß aber nicht wie: </p><p> Zu ersetzende Zeichen: </p> <pre class="brush:php;toolbar:false;">first end | <Tag> | <red> | </> <p><code>day => Holen Sie sich das aktuelle Datum (zum Beispiel: 14)</code></p><p> <code>red => Farbe rot</code> <code><a ###https://www.google.com/>Link</> ;/></code></p> <p><code>Geben Sie ein: Hallo<red>Herr Siro</red></code> <code>Ausgabe: Hallo<span style="color: red">Mr. Siro</span></code></p> <p>Mein Chatverlauf. </p> <p>Können Sie mir sagen, wie ich eine generische Funktion schreiben kann, um zu prüfen, ob das obige Tag ersetzt wird? Das ist mein Code: </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) => ); 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>` ); } }); Inhalt zurückgeben; };</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="{ Klassenname: currentUserId === msg.senderId ? 'message-external-link' : '', }" /></code></pre> </p> <p>Leider ist mein Englisch nicht sehr gut! </p><p> Danke euch allen! </p>
P粉330232096P粉330232096388 Tage vor461

Antworte allen(1)Ich werde antworten

  • 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()],
        [/<([^>]+)>([^<]+)<\/\1>/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 />

    Antwort
    0
  • StornierenAntwort