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