Rumah  >  Soal Jawab  >  teks badan

Cara menggantikan teg yang dipratentukan secara automatik

<p>Saya mempunyai beberapa aksara yang perlu diganti seperti di atas, tetapi saya tidak tahu caranya: </p><p> Aksara untuk diganti: </p> <pre class="brush:php;toolbar:false;">first | <hari> <merah> | <a ###> </> <p><kod>hari => Dapatkan tarikh semasa (contohnya: 14)</code></p><p> <kod>merah => warna merah</kod> <kod><a ###https://www.google.com/>Pautan</> ;/></code></p> <p><kod>Masukkan: Hello<red>En Siro</red></code> <kod>Output: Hello<span style="color: red">En. Siro</span></code></p> <p>Sejarah sembang saya. </p> <p>Bolehkah anda memberitahu saya cara menulis fungsi generik untuk menyemak penggantian teg di atas? Ini kod saya: </p> <p> <pre class="snippet-code-js lang-js prettyprint-override"><code>export const formatTags = (kandungan) => const firstTag = "<merah>"; const secondTag = "</red>"; const tagsIndex = [...content.matchAll(new RegExp(firstTag, "gi"))].map( (a) => ); const initialContent = kandungan; tagsIndex.forEach((index) => { const tagContent = initialContent.substring( indeks + firstTag.length, initialContent.indexOf(secondTag, index) ); if (firstTag === "<merah>") { kandungan = content.replaceAll( `${firstTag}${tagContent}${secondTag}`, `<span style="color: red">${tagContent || "わからない"}</span>` ); } }); mengembalikan kandungan; };</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 ? 'mesej-pautan-luar' : '', }" /></code></pra> </p> <p>Maaf Bahasa Inggeris saya tidak begitu baik! </p><p> terima kasih semua! </p>
P粉330232096P粉330232096388 hari yang lalu465

membalas semua(1)saya akan balas

  • P粉388945432

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

    Panggil balik fungsi gantian yang digunakan dalam Map。用于捕获文本的正则表达式将是键,replace anda boleh membuat peraturan penggantian ialah nilainya. Gelung melalui peraturan dan kemas kini rentetan.

    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 />

    balas
    0
  • Batalbalas