Skip to content

Instantly share code, notes, and snippets.

@jakobloekke
Created November 4, 2013 14:25
Show Gist options
  • Save jakobloekke/7303217 to your computer and use it in GitHub Desktop.
Save jakobloekke/7303217 to your computer and use it in GitHub Desktop.
Angularjs sprintf-style filter for interpolating text with values.
app.filter('sprintf', function() {
function parse(str) {
var args = [].slice.call(arguments, 1),
i = 0;
return str.replace(/%s/g, function() {
return args[i++];
});
}
return function(str) {
return parse(str, arguments[1], arguments[2], arguments[3], arguments[4], arguments[5]);
};
});
// Usage:
$filter('sprintf')(
"Hello %s. It's %s to see you!",
"World",
"very"
);
@miukki
Copy link

miukki commented Jun 3, 2015

.filter('sprintf', function() {

function parse(str, args) {
    var i = 0;
    return str.replace(/%s/g, function() { return args[i++] || '';});
}

return parse(Array.prototype.slice.call(arguments, 0,1)[0], Array.prototype.slice.call(arguments, 1));

});

@saschahepp
Copy link

@miukki your adaption only partly works for me (angularjs 1.3). But if I adapt it a little, it works:

app.filter('sprintf', function() {

    function parse(str, args) {
        var i = 0;
        return str.replace(/%s/g, function() { return args[i++] || '';});
    }

    return function() {
        return parse(Array.prototype.slice.call(arguments, 0,1)[0], Array.prototype.slice.call(arguments, 1));
    };
});

Usage:
{{ 'Hello %s' | sprintf : 'World' }}

thx!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment