正则表达式 <h2>kk</h2> 替换为 <h2 id="kk">kk</h2>

`<h2>kk</h2><h2>k333k</h2>`.replace(/\<h2>(.*?)<\/h2>/g, `<h2 id='$1'>$1</h2>`)

后面可以是个函数

`<h2>kk</h2><h2>k333k</h2>`.replace(/\<h2>(.*?)<\/h2>/g, function (itemA, a1) {
console.info('itemA', itemA, a1)
return `<h2 id='${a1}'>${a1}</h2>`
})

中文的id不能跳转,加个转码

this.html = md.render(module.default).replace(/\<h2>(.*?)<\/h2>/g, function (itemA, a1) {
          console.info('itemA', itemA, a1)
          return `<h2 id='${escape(a1)}'>${a1}</h2>`
        })
posted @ 2023-03-13 14:23  彭成刚  阅读(22)  评论(0编辑  收藏  举报