想在html中的的src的相对路径中<img src="/Images/IMG_8506_副本.jpg" alt="">添加绝对路径,

首先获用正则获取img标签:

/<img [^>]*src=['"]([^'"]+)[^>]*>/gi

得到的结果为:

<img src="/Images/IMG_8506_副本.jpg" alt="">

 

然后再获取src:

/src=[\'\"]?([^\'\"]*)[\'\"]?/gi

得到结果为:

src="/Images/IMG_8506_副本.jpg"

最后还要排除src路径为“../../Images/IMG_8506_副本.jpg"以及绝对路径的情况:

(n.indexOf("http://") !== -1)? src:("src='" +"http://www.xhdgis.com" +n.replace(/[.]{2}\/[.]{2}/, "") +"'");

最后返回的结果即为想要的img路径。

 

代码:

    Content = res.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi,function(match, capture) {
            if (match)
              return match.replace(/src=[\'\"]?([^\'\"]*)[\'\"]?/gi, function(src,n) {
                //去除相对路径../..  同时排除绝对路径
                return  (n.indexOf("http://") !== -1)? src:("src='" +"http://www.xhdgis.com" +n.replace(/[.]{2}\/[.]{2}/, "") +"'");
              });
          }
        );

 

posted on 2018-03-26 11:45  dqy95  阅读(908)  评论(0)    收藏  举报