js正则给代码块添加编号

js正则给代码块添加编号

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 替换方法
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);
}