2015-02-11 119 views
1

我想用带有img标签的字符串替换所有图像路径的javascript。我需要一个reg exp或者脚本吗?用<img src="">替换../IMG/xEPI_STOPPED_TOT.gif

图像名称和分机可以在我的字符串中不同。换句话说,我有不同的图像。

更换../IMG/epi.gif与

<img src="img/epi.gif"> 

初始字符串

“此图片../IMG/epi.gif该图像../IMG/secondImage.jpg是不好”

需要的结果将是

'This image <img src="img/epi.gif"/> and this image <img src="img/secondImage.jpg"/> are not good' 
+0

是图像路径故意的lowercasing? – jurgemaister 2015-02-11 08:16:27

+0

是的这也是../缺少 – ACe 2015-02-11 08:17:25

+0

顺便说一下,所有图像以../IMG开头,它们以扩展名.gif或.jpg结尾...... – ACe 2015-02-11 08:18:22

回答

1

试试这个:

更新

var img = 'This image ../IMG/epi.gif and this image ../IMG/secondImage.jpg are not good'; 
 
var newImg = img.replace(/\.\.\/IMG\/([^\.]+)(\.jpg|\.gif)/gi, '<img src="img/$1$2">'); 
 
alert (newImg);

+0

对不起,我已经尝试过,这仍然不适用于此字符串“此图像../IMG/epi.gif和此图像../IMG/secondImage.jpg不好” – ACe 2015-02-11 09:22:16

+0

@ACe检查我的更新 – 2015-02-11 09:29:46

+0

感谢您的帮助!它看起来像工作 – ACe 2015-02-11 10:28:27

0

var img = '../IMG/xEPI_STOPPED_TOT.gif'; 
 
var newImg = img.replace(/\.\.\/IMG\/(.*)/, '<img src="img/$1">'); 
 
alert (newImg);

+0

什么?它匹配../IMG/ – 2015-02-11 08:38:10

+1

对不起。太早了。我会去喝更多的咖啡 – jurgemaister 2015-02-11 08:38:31

+0

虽然我并不完全没有。在字符串asdfasdf asdfasdf asdfasdf ../IMG/xEPI_STOPPED_TOT.gif asdf'上试试。你会在最后抓到'asdf',所以你需要将文件扩展名作为分隔符。 – jurgemaister 2015-02-11 08:40:04