AngularJS text filter (with C# string.format() syntax)

Posted by ryansouthgate on 13 Sep 2016

If you’ve read a few posts from my blog you’ll probably see that I’ve done a bit of work in the .Net world. My day job requires me to use the .Net Framework for server side programming. I’ve spent a lot of time using C# and enjoy the language.

I’ve also been doing a lot of work in the JavaScript (front-end) world recently. Primarily using the AngularJS framework.

By the end of this post you’ll be able to use C#’s string.Format() standard in JavaScript and as an AngularJS filter.

I was trumped recently by JavaScipt’s string.replace - I hate it, why you would call a method called replace (using a string argument) and have it only replace the first instance of the matched string is beyond me!

Seriously hate it! I’m going to stop looking at it as I can feel myself getting wound up again….

Here’s an example of what I mean:


Anyway….so the way to get around this failing is to use Regex. I’ve never taken the time to properly understand Regex (does anyone really understand Regex??) - but I can muddle through…

So let’s get down to the core matter. I really like the syntax of C#’s string.Format() - plus it saves me creating a “custom” standard for ourselves. Also, since we have a lot of C# developers at my workplace - this seemed like a brilliant opportunity to bring the familiarity to JavaScript.

I’m going to wrap the “replace functionality” inside an AngularJS filter and show usage.

Here’s the code in a gist commented with the explanation.

Looking at the code, the main bits are really inside the for-loop. That’s where all the replacing occurs, the rest of the code is just the AngularJS filter code. So if you aren’t living in an Angular World then just rip out the for loop and modify to your needs.

Here’s a working Plunker too, which shows injecting both a string value (in the HTML) and a value that lives on the controller’s scope:

If you’ve got any questions, comments or improvements then get hold of me on Twitter

comments powered by Disqus