1

I wrote some days ago a simple thing to fallback to an placeholder image if the desired image can't loaded. It allows the user to use 2 placeholders to to define the image size:

That's the 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);
    });
};

I'm asking me now, if it is possible to replace .replace('$w', this.width).replace('$h', this.height); with an shorter but equal regex to replace all $* (dollar + first-char) with an assigned value from any object?

Something like this:

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

So that we can use all properties from the image-object, e.g. image.width, image.src, image.width...

Community
  • 1
  • 1
yckart
  • 32,460
  • 9
  • 122
  • 129

1 Answers1

1

Only if you use a function as the replacement. Like:

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

You could also do away with the comparison like this:

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

If you want to look up a value in a hash you could use:

"$w/$h".replace(/\$(\w+)/g, function(m, name){ return hash[name]; });
Qtax
  • 33,241
  • 9
  • 83
  • 121
  • Mhh, this makes it not more dynamically. It limits the replacments to `$w` and `$h` ;) I've updated my question... – yckart Jul 01 '13 at 10:36
  • @yckart, the function can obviously do anything you want. I'll add an example. – Qtax Jul 01 '13 at 10:38
  • Okay, I'll remove it again :) – yckart Jul 01 '13 at 10:48
  • Another thing, is it somehow possible to catch something like `$f` but get all things from the `object` which starts with `f`? So we match `$f` but catch `obj.foo` instead of `obj.f`? – yckart Jul 01 '13 at 10:51