2013-07-01 28 views
1

我幾天前寫了一個簡單的東西來回退到佔位符圖像,如果無法加載所需的圖像。它允許用戶使用2個佔位符來定義圖像尺寸:用相同的命名變量替換字符串

這就是thing I wrote

;(window.jQuery || window.Zepto).fn.fallback = function (url) { 
    return this.one('error', function() { 
     this.src = (url|| 'http://lorempixel.com/$w/$h') 
     .replace('$w', this.width).replace('$h', this.height); 
    }); 
}; 

我在問我,現在,如果有可能有更短的更換.replace('$w', this.width).replace('$h', this.height);但等於regex用來自任何對象的指定值替換全部$*(美元+第一個字符)?

事情是這樣的:

'$f is not equal to $b'.replace(/magicregex/, { 
    foo: 'foo', 
    bar: 'bar' 
}); 

這樣我們就可以使用所有propertiesimage-object,例如image.width,image.src,image.width ...

回答

1

只有當您使用函數作爲替換。像:

"$w/$h".replace(/\$[wh]/g, function(m){ return m == "$w" ? width : height; }); 

你也可以通過這樣的比較做掉:

"$w/$h".replace(/\$(?:(w)|h)/g, function(m, w){ return w ? width : height; }); 

如果你想要查找的哈希值,你可以使用:

"$w/$h".replace(/\$(\w+)/g, function(m, name){ return hash[name]; }); 
+0

MHH,這使得它不會更動態。它將替換限制爲'$ w'和'$ h';)我更新了我的問題...... – yckart

+0

@yckart,該函數顯然可以做任何你想要的。我會添加一個例子。 – Qtax

+0

是的,你最後的編輯看起來不錯!謝謝:) – yckart