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