2016-01-10 85 views
0

我想更換CSS背景的URL像這樣:更換CSS背景鏈接

body { 
    background: url("../common/images/nyau.jpg") center center; 
} 
.alma { 
    background: url("./vau/vau.jpg"); 
} 
.ata { 
    background: url("./mak.jpg"); 
} 

這些:

body { 
    background: url("./images/nyau.jpg") center center; 
} 
.alma { 
    background: url("./images/vau.jpg"); 
} 
.ata { 
    background: url("./images/mak.jpg"); 
} 

可惜我不熟悉的正則表達式的。

我知道我可以選擇("../common/images/nyau.jpg")這部分與/\((.*?)\)/g,但我需要從最後/(nyau.jpg)以某種方式捕獲部分。所以我可以做./images/$1或類似的東西。

編輯:在api of gulp-replace我只允許使用沒有任何javascript函數的正則表達式。

+2

什麼是每個'background'屬性的單獨的行目的是什麼?最後的背景設置會覆蓋前兩個 – guest271314

+1

'bg ='./images/'+ bg.split('/')。pop()' – adeneo

+0

@adeneo我們都有同樣的想法 – CoderPi

回答

1

此功能fixPath(path)將返回您所需的路徑,然後您可以應用它,無論您需要修復背景。

function fixPath(path) { 
 
    return path.replace(/(.*\/)(.*)$/, "./images/$2") 
 
    // return "./images/" + path.split("/").pop() 
 
} 
 

 
// Demo Paths 
 
var paths = ["../common/images/nyau.jpg", "./vau/vau.jpg", "./mak.jpg"] 
 

 
// Do it for all paths 
 
paths = paths.map(fixPath) 
 

 
// Demo Output 
 
document.write(JSON.stringify(paths))

+0

不幸的是,我只能使用正則表達式和沒有JavaScript函數 – tsm

+0

@AttilaEgyed是這樣的?但是,好吧,我會找到正則表達式 – CoderPi

+0

@CodeSir check regexr.com,我使用'gulp-replace',並且在那個API中我只允許使用沒有任何javascript函數的正則表達式 – tsm