仅获取具有相对路径的图像|定期表达

时间:2019-01-16 12:00:34

标签: javascript regex

我试图从字符串中提取具有相对路径('/folder/image.jpg', 'someimage.png')而不是绝对路径(https://www.example.com/abc.jpg)的图像,然后将所有图像压入某个数组。

当前数组: ["123.png", "abc.jpg", "xyz.jpg", "http://example.com/abc.jpg", "https://example.com/xyz.jpg", "popcorn.png"]

预期数组: ["123.png", "abc.jpg", "xyz.jpg", "popcorn.png"]

测试:https://codepen.io/Ashish9342/pen/qLwWYz?editors=0011

var content = 'Lorem ipsum dolor sit amet, consectetur <img style="height:10px" src="123.png"/> adipiscing elit. Praesent sed orci vitae nulla ultricies vehicula. Donec ex arcu, ultricies at nisl et, convallis lobortis nisl. Pellentesque aliquet luctus mollis. <img src="abc.jpg"/> Ut vehicula, lectus et iaculis molestie, est purus dignissim magna, sit amet tincidunt quam ante varius neque. Pellentesque quis ligula <img class="fantom" src="xyz.jpg"/> in risus efficitur ullamcorper. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Duis porta, eros at sollicitudin viverra, nisl lectus dapibus erat, id rutrum augue augue sed lectus. <img src="http://example.com/abc.jpg"/> Nullam felis augue, placerat vel mattis et, viverra sit amet elit. Cras pulvinar iaculis massa, sed consectetur <img src="https://example.com/xyz.jpg"/> ligula luctus non. Donec vel augue mattis tellus rutrum ultricies et suscipit  <img src="popcorn.png" alt="pop corn"/> erat.'

function getRelativePathImages(content) {
  if (content && content.search('<img')) {
    const urls = [];
    let m;
    const rex = /<img[^>]+src="([^">]+)/g;
    // const rex = /<img[^>]+src="([^http">]+)/g;

    while (m = rex.exec(content)) {
      if (urls.indexOf(m[1]) < 0) {
        urls.push(m[1]);
      }
    }
    console.log(urls);
  }
}

getRelativePathImages(content);

2 个答案:

答案 0 :(得分:1)

只需在'config': { 'gceClusterConfig': { "metadata": { "bigquery-connector-version": "0.12.1", "gcs-connector-version": "1.8.1" } } } 之后的正则表达式(?!http)中使用负向查找,这将拒绝以src="开头的所有网址,并将正则表达式更改为

http

/<img[^>]+src="(?!http)([^">]+)/g

答案 1 :(得分:0)

如果不需要的路径以http开头,则不需要正则表达式。只需使用startsWith方法:

s = "http://example.com/abc.jpg";
if(!s.startsWith("http")){
  // add s to you array of URLs
}