P粉3889454322023-09-04 09:34:29
您可以创建替换规则的Map
。用于捕获文本的正则表达式将是键,replace
中使用的替换函数回调将是值。循环遍历规则并更新字符串。
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 />