Home  >  Q&A  >  body text

How to automatically replace predefined tags

<p>I have some characters that need to be replaced as above, but I don't know how: </p><p> Characters to replace: </p> <pre class="brush:php;toolbar:false;">first | end | <day> | | <red> | </red>| <a ###> | </> |</pre> <p><code>day => Get the current date (for example: 14)</code></p><p> <code>red => color red</code> </p><p> <code><a ###https://www.google.com/>Link</> => <a href="https://www.google.com/"> Link</></code></p> <p><code>Enter: Hello<red>Mr. Siro</red></code> </p><p> <code>Output: Hello<span style="color: red">Mr. Siro</span></code></p> <p>My chat history. </p> <p>Can you tell me how to write a generic function to check for replacement of the above tag? This is my 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) => 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>Sorry my English is not very good! </p><p> thank you all! </p>
P粉330232096P粉330232096388 days ago464

reply all(1)I'll reply

  • P粉388945432

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

    You can create a Map of replacement rules. The regular expression used to capture the text will be the key and the replace function callback used in replace will be the value. Loop through the rules and update the string.

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

    reply
    0
  • Cancelreply