[Vuejs]-How to automatically replace a tag predefined

3👍

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

Leave a comment