鍍金池/ 問答/HTML5  HTML/ 字符串中解析匹配Html標(biāo)簽問題

字符串中解析匹配Html標(biāo)簽問題

需求: 需求是將字符串中一個(gè)img標(biāo)簽換成img標(biāo)簽的一個(gè)屬性(name)
示例:

aaaaaaaaaaaa
<img name="U+1F608" src="../../static/images/emoji/1f608.png" style="width: 18px;height: 18px;margin: 2px;">
bbbbbbbbbbbbb
<img name="U+1F609" src="../../static/images/emoji/1f609.png" style="width: 18px;height: 18px;margin: 2px;">
cccccccccccccc

可以看到這個(gè)字符串是 aaaaaaaaaImg標(biāo)簽bbbbbbImg標(biāo)簽cccccc,
結(jié)果要求是aaaaaaU+1F608bbbbbbbbbU+1F609cccccccccccccc

嘗試:感覺正則匹配還是可以的,但是怎么匹配到且替換為name屬性這個(gè)就有點(diǎn)兒困難

回答
編輯回答
命多硬

不用正則,用 DOM API也可以,最近喜歡嘗試奇技淫巧

let str = `aaaaaaaaaaaa
<img name="U+1F608" src="../../static/images/emoji/1f608.png" style="width: 18px;height: 18px;margin: 2px;">
bbbbbbbbbbbbb
<img name="U+1F609" src="../../static/images/emoji/1f609.png" style="width: 18px;height: 18px;margin: 2px;">
cccccccccccccc`
let div = document.createElement('div')
div.innerHTML = str
Array.from(div.children).forEach(img => {
  div.replaceChild(document.createTextNode(img.name), img)
})
console.log(div.innerHTML.replace(/\s/g, ''))

2017年6月13日 14:36
編輯回答
焚音

自己給出完整的答案

let str = 'aaaaaaaaaaaa\n' +
  '<img name="U+1F608" src="../../static/images/emoji/1f608.png" style="width: 18px;height: 18px;margin: 2px;">\n' +
  'bbbbbbb<img name="U+1F609" src="../../static/images/emoji/1f609.png" style="width: 18px;height: 18px;margin: 2px;">bbbbbb\n' +
  '<img name="U+1F609" src="../../static/images/emoji/1f609.png" style="width: 18px;height: 18px;margin: 2px;">\n' +
  'cccccccccccccc'
/* 方式1 */
// 匹配圖片(g表示匹配所有結(jié)果i表示區(qū)分大小寫)
let imgReg = /<img.*?(?:>|\/>)/gi
// 匹配src屬性
let nameReg = /name=['"]?([^'"]*)['"]?/i
let arr = str.match(imgReg)
// console.log('所有已成功匹配圖片的數(shù)組:' + arr)
for (let i = 0; i < arr.length; i++) {
  // console.log(arr[i])
  let names = arr[i].match(nameReg)
  // 獲取圖片地址
  if (names && names[1]) {
    // console.log('已匹配的圖片地址' + (i + 1) + ':' + names[1])
    str = str.replace(arr[i], names[1])
  }
}
console.log(str)
/* 方式2 */
let newStr = str.replace(/<img.*?>/mg, s => {
  let matchs = s.match(/\(?<=name.*?=.*?\)('|").*?\1/)
  return matchs ? matchs[0].slice(1, -1) : ''
})
console.log(newStr)
2018年9月13日 07:43
編輯回答
葬愛
let newStr = str.replace(/<img.*?>/mg, (s) => {
  let matchs = s.match(/(?<=name.*?=.*?)('|").*?\1/);
  return matchs ? matchs[0].slice(1, -1) : '';
});
2017年10月29日 04:18