JavaScript中的正则表达式 - 替换Image src属性 [英] Regular expression in JavaScript - Replace Image src attribute

查看:150
本文介绍了JavaScript中的正则表达式 - 替换Image src属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中,我有一个包含DOM片段的字符串。如何查找和替换图像的src属性?

In JavaScript I have a string containing a DOM fragment. How would I find and replace the src attribute of an image?

我想用新路径替换所有图像的路径,但保留图像名称。并非所有路径都相同,可以来自不同的位置。
我的正则表达能力最差。

I would like to replace the path of all images with a new path but keeping the image name. Not all the paths are the same and can come from various locations. My regular expression skills are poor at best.

例如:

Change

   <img src='path/to/image/name.jpg' />

into 

   <img src='newPath/name.jpg' />


推荐答案

试试这个:

str.replace(/src='(?:[^'\/]*\/)*([^']+)'/g, "src='newPath/$1'");

这篇关于JavaScript中的正则表达式 - 替换Image src属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆