Home > Software design >  how to automatically replace a tag predefined
how to automatically replace a tag predefined

Time:12-14

I have some characters that need to be replaced as above but I don't know how:
characters to replace:

first   |  end  |
<day>   |       |
<red>   | </red>|
<a ###> | </>   |

day => get now day (ex: 14)
red => color red
<a ###https://www.google.com/>link</> => <a href="https://www.google.com/">link</>

input: hello <red>Mr.Siro</red>
output: hello <span style="color: red">Mr.Siro</span>

my chat.

Can you show me how to write a common function to check the replacement of the above tags? here is my 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;
};

<span
   :
   v-html="msg.text"
   v-linkified:options="{
    className: currentUserId === msg.senderId
     ? 'message-external-link'
     : '',
   }"
/>

sorry my english is not so good !
thanks all!

CodePudding user response:

You could create a Map of the replacement rules. The regex used to capture the text will be the key and the replacer function callback to be used in replace will 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()],
    [/<([^>] )>([^<] )<\/\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 />

  • Related