2015-02-11 118 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