js正则搜索img标签并替换src值

2023-11-12

第一种用函数更灵活

const html = '<img src="image1.jpg" data-a="aa"><img src="image22.jpg" data-a="a2a"><p>Some text with no image</p><img src="i23mage3.jpg"  1  >';

const regex = /(<img.*?src=")(.*?)(".*?>)/g; //用于匹配<img>标签中的src属性的正则表达式
const matches = html.match(regex); //使用match()方法获取匹配结果

var res=html.replace(regex,function(a,b,c,d){
    //a是整体
    //b是第一个分组
    //c是第二个分组
    //d是第三个分组
    if(c.startsWith('image')){
        return b+'嘎嘎'+c+d
    }
    return a
})

console.log(res); //输出<img src="嘎嘎image1.jpg" data-a="aa"><img src="嘎嘎image22.jpg" data-a="a2a"><p>Some text with no image</p><img src="i23mage3.jpg"  1  >

第二种字符串拼接

const html = '<img src="image1.jpg" data-a="aa"><img src="image22.jpg" data-a="a2a"><p>Some text with no image</p><img src="i23mage3.jpg"  1  >';

const regex = /(<img.*?src=")(.*?)(".*?>)/g; //用于匹配<img>标签中的src属性的正则表达式
const matches = html.match(regex); //使用match()方法获取匹配结果



var sources = matches.map(match => match.replace(regex, '$2')); //$序号从1开始,$1为第一个分组
var sources = matches.map(match => match.replace(regex, '$1$2'+'好$3')); //


console.log(sources)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

js正则搜索img标签并替换src值 的相关文章

随机推荐