javascript - 从字符串中取出图像标签并将其放入数组中
问题描述
需要处理一个很奇怪的字符串响应。我需要从该字符串中取出所有图像标签并将它们放入一个数组中,这样我就可以遍历该数组,以便渲染图像
示例字符串
var str = '<p>↵ This is the cap you unscrew to open when you refuel your car↵</p>↵↵<p>↵ New line↵</p>↵↵<p>↵ <img alt="blah" src="https://www.imgone.com/wp-content/uploads/2011/04/Tyre-Illustration-500.jpg" />↵</p>Random Text <img alt="blah" src="https://www.imgtwo.com/wp-content/uploads/2011/04/Tyre-Illustration-500.jpg" />'
预期的结果可以是
['<img alt="blah" src="https://www.imgone.com/wp-content/uploads/2011/04/Tyre-Illustration-500.jpg" />', '<img alt="blah" src="https://www.imgtwo.com/wp-content/uploads/2011/04/Tyre-Illustration-500.jpg" />']
解决方案
您可以像这样使用/<img .*?>/g
andexec
来检查匹配
var str = '<p>↵ This is the cap you unscrew to open when you refuel your car↵</p>↵↵<p>↵ New line↵</p>↵↵<p>↵ <img alt="blah" src="https://www.imgone.com/wp-content/uploads/2011/04/Tyre-Illustration-500.jpg" />↵</p>Random Text <img alt="blah" src="https://www.imgtwo.com/wp-content/uploads/2011/04/Tyre-Illustration-500.jpg" />'
var m;
var result = []
do {
m = re.exec(str);
if (m) {
result.push(m[0]);
}
} while (m);
//var tmp = str.replace(/<img .*?>/g,"");
console.log(result)
var re = /<img .*?>/g;
var str = '<p>↵ This is the cap you unscrew to open when you refuel your car↵</p>↵↵<p>↵ New line↵</p>↵↵<p>↵ <img alt="blah" src="https://www.imgone.com/wp-content/uploads/2011/04/Tyre-Illustration-500.jpg" />↵</p>Random Text <img alt="blah" src="https://www.imgtwo.com/wp-content/uploads/2011/04/Tyre-Illustration-500.jpg" />'
var m;
var result = []
do {
m = re.exec(str);
if (m) {
result.push(m[0]);
}
} while (m);
//var tmp = str.replace(/<img .*?>/g,"");
console.log(result)
推荐阅读
- python - 逐字输出 Python
- php - 无法在 Nginx 上使用 Laravel 在 PhpStorm 中触发 Xdebug 中断
- youtube-data-api - YouTube 数据 API v3 显示配额 0 / 0
- botframework - 在 Bot Composer 中向聊天机器人添加反馈
- docker - Cronjob 未通过 Crontab -e 运行
- go - 关闭通道退出多个 go 例程?
- google-apps-script - 每 X 分钟自动运行一个脚本
- html - 表单输入大小
- python-3.x - 合并熊猫数据框中的两列或多列
- c++ - 数字中的不同元素