使用正则获取 <> 之间的图片链接
在给定的文本中获取 <> 之间的图片链接,可以使用正则表达式来实现。以下提供了几种正则表达式解决方案:
// 匹配第一个 <> 之间的图片链接 const regex1 = /<imgs*src="([^"]+)"s*/*>/; // 匹配所有 <> 之间的图片链接 const regex2 = /<imgs*src="([^"]+)"[ss]*?>/g;
使用正则表达式示例
const string = '<p>唉算阿萨德阿萨德阿萨德阿萨德阿萨德阿萨德阿萨德撒旦撒旦说道阿萨德说道阿萨德阿萨德阿萨德阿萨德阿萨德阿萨德阿萨德撒旦阿萨德撒旦阿萨德撒旦阿萨德是阿萨德<img src="http://p9.pccoo.cn/webapp/20161230/2016123010375539992519_300_300.gif" /><img src="http://p9.pccoo.cn/webapp/20161230/2016123010380668807050_300_300.gif" /></p>'; // 匹配第一个链接 console.log(regex1.exec(string)[1]); // 匹配所有链接 console.log([...regex2.exec(string).slice(1)]);
输出结果
http://p9.pccoo.cn/webapp/20161230/2016123010375539992519_300_300.gif [ "http://p9.pccoo.cn/webapp/20161230/2016123010375539992519_300_300.gif", "http://p9.pccoo.cn/webapp/20161230/2016123010380668807050_300_300.gif" ]