Skip to content

Instantly share code, notes, and snippets.

@litera
Created March 19, 2014 03:25
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save litera/9634958 to your computer and use it in GitHub Desktop.
Save litera/9634958 to your computer and use it in GitHub Desktop.
string.Format for AngularJS
/* AngularJS string.Format filter
*
* This filter provides string variable replacement similar to C# string.Format("{0}", "something");
*
* Usage: {{ "From model: {0}; and a constant: {1};" | format:model.property:"constant":...:... }}
*/
(function (angular) {
angular
.module("ng")
.filter("format", function () {
return function (input) {
var args = arguments;
return input.replace(/\{(\d+)\}/g, function (match, capture) {
return args[1*capture + 1];
});
};
});
})(angular);
@Nate-Wilkins
Copy link

1*capture...? Isn't 1 * anything = anything

@miller45
Copy link

Just tried it in the console (enter the funny "typeless" world of javascript)
"1"+1 ="11"
1_"1"+1=2
so the 1_capture forces javascript to evaluate capture as number and then adds 1 resulting in a number.
else "1"+1 means append 1 to the string "1".

@Nate-Wilkins
Copy link

@miller45 thanks!
So recant PEMDAS still applies even when the variables aren't numbers

1*"3"+1 = 4

@markogresak
Copy link

Use args[parseInt(capture, 10) + 1] which is understood by everyone, not some type conversion magic.

@adrianoxavier
Copy link

For "typeless" use:

args[Number(capture) + 1]

@bdairy
Copy link

bdairy commented Feb 9, 2016

how to call this filter inside the controller

@alisonjonck
Copy link

I guess you probably found a solution for that, however I will answer that for any future questions:

You can use that through $filter. In your controller parameters inject $filter so you can use any filter inside your controller by simply passing its name as a parameter, like this:

var value = $filter('filterName')(input);

@sorskoot
Copy link

sorskoot commented Aug 2, 2016

Instead of using Number() for the parsing to a number you can add a + in front of it. Like return args[+capture + 1];

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