您好我想捕捉img src =“...”之间的所有内容,但不确定为何下面的代码无法正常工作
var stringHtml = '<img src="content://media/external/images/media/21260"><img src="content://media/external/images/media/21260"><img src="content://media/external/images/media/21260">';
var srcArray = ['x.png', 'y.png', 'z.png']
var rgx = /<img src="([^"]+)"/g;
var match;
for (var a = 0; a < srcArray.length; a++) {
match = rgx.exec(stringHtml);
stringHtml = stringHtml.replace(match[1], srcArray[a]);
}
alert(stringHtml);
答案 0 :(得分:3)
经常回答don't use regex to parse html。相反,解析字符串并轻松可靠地获取src
var stringHtml = '<img src="content://media/external/images/media/21260"><img src="content://media/external/images/media/21260"><img src="content://media/external/images/media/21260">';
const parser = new DOMParser().parseFromString(stringHtml, 'text/html');
for (let img of parser.getElementsByTagName('img')) {
console.log(img.src);
}