js正则给代码块添加编号 发表于 2019-12-11 | 更新于 2023-01-11 js正则给代码块添加编号12345678910111213141516// 替换方法function replacer(str = "", name, content) { let i = 1; const n = m => `<em class="row-num">${m > 9 ? m : "0" + m}</em>`; const c = content.replace(/\n/g, function() { i += 1; return `</p><p class="code-row">${n(i)}`; }); const res = `<p class="code-row">${n(1)}${c}</p>`; return `<code${name}>${res}</code>`;}// 添加编号export default function codeLines(codeStr = "") { return codeStr.replace(/<code([^>]*)>([\s\S]*?)<\/code>/g, replacer);}