search

Home  >  Q&A  >  body text

javascript - How to extract the alt value of image tags using regular js

var aa="Hello<img src='aaa.gif' alt='Picture 1'>The weather is good<img src='bbb.gif' alt='Picture 2'> Ha ha"

With the above code, what I ultimately want to get using regular expressions is the following text
Hello Picture 1 The weather is good Picture 2 Haha
How should I write it?
What I can think of is to use replace, but I really don’t know how to match img and extract alt information. Please help~

给我你的怀抱给我你的怀抱2815 days ago740

reply all(1)I'll reply

  • 高洛峰

    高洛峰2017-05-19 10:47:13

    var reg = /(.*?)<img.+?alt=('|")(.*?).*?>([^<]*)/gi;
    var str = "你好<img src='aaa.gif' alt='图1'>天气不错<img src='bbb.gif' alt='图2'>哈哈"
    var resultStr = ''
    var exec = ''
            
    while(exec = reg.exec(str)) {
        resultStr += exec[1] + exec[3] + exec[4]
    }
            
    console.log(resultStr)

    reply
    0
  • Cancelreply