js使用正则从字符串中取出img标签

要使用正则表达式从字符串中提取<img>标签,您可以使用以下代码:

const str = `Some text <img src="image.jpg" alt="Image"> and more text <img src="another.png" alt="Another">`;
const regex = /<img[^>]*>/g;
const imgTags = str.match(regex);
 
console.log(imgTags);

 

这段代码会输出一个包含字符串中所有<img>标签的数组。如果您只想提取src属性的值,可以稍微修改正则表达式:

const str = `Some text <img src="image.jpg" alt="Image"> and more text <img src="another.png" alt="Another">`;
const regex = /src="([^"]*)"/g;
let src;
 
while ((src = regex.exec(str)) !== null) {
  console.log('src:', src[1]);
}

这段代码会输出每个<img>标签的src属性值。

 
posted @ 2024-03-26 16:10  维维WW  阅读(950)  评论(0)    收藏  举报