The problem of parsing matching Html tags in strings

requirement: requirement is to replace an img tag in a string with an attribute of the img tag (name)
example:

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

you can see that this string is aaaaaaaaa Img tag bbbbbb Img tag cccccc,
result requires aaaaaa U+1F608 bbbbbbbbb U+1F609 cccccccccccccc

try: feels that regular matching is OK, but how to match and replace it with the name attribute is a bit difficult

Mar.06,2021

let newStr = str.replace(/<img.*?>/mg, (s) => {
  let matchs = s.match(/(?<=name.*?=.*?)('|").*?\1/);
  return matchs ? matchs[0].slice(1, -1) : '';
});

you don't have to be regular, but you can use DOM API. Recently, you like to try tricks and tricks

.
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, ''))


give yourself a complete answer

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 */
// gi
let imgReg = /<img.*?(?:>|\/>)/gi
// src
let nameReg = /name=['"]?([^'"]*)['"]?/i
let arr = str.match(imgReg)
// console.log(':' + arr)
for (let i = 0; i < arr.length; iPP) {
  // 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)
Menu