Rob Allred

Developer, Outdoor Enthusiast & Purveyor of Odd Things. AngularJS, Javascript, ASP_NET, OrchardCMS.

  • Twitter

Javascript Pitfalls for C# Programmers Part 3

Posted on August 21, 2015

One thing I really miss from C# when I am working in JavaScript is String.format!

I found this little code snippet floating around the internet in many forms, but this one has been working well enough for me.

1
2
3
4
5
6
7
8
9
10
11
if (!String.format) {
        String.format = function(format) {
            var args = Array.prototype.slice.call(arguments, 1);
            return format.replace(/{(\d+)}/g, function(match, number) {
                return typeof args[number] != 'undefined'
                  ? args[number]
                  : match
                ;
            });
        };
    }

Once the function is define (see above code) it is really easy to use like I am used to in C#

1
String.format('{0} is the amount of times I have used this function on {1}!', 7, 'this page');

The out put from above will look like this:

7 is the amount of times I have used this function on this page!

I have seen people suggest modifying String’s prototype, but I like the way it looks in C#. I would rather just cut and past this little snippet than reference some external framework, unless I get it for free in jquery or angularjs.

Let me know what you think.

Filed Under: javascript Tagged With: Code Snippets, javascript, Javascript for C# Programmers, tutorials

Categories

  • Accessibility (1)
  • anjularjs (5)
  • Asp.Net (3)
  • CSharp (2)
  • CSS (1)
  • Database (3)
  • Github (1)
  • Html5 (1)
  • javascript (11)
  • Linq (1)
  • Orchard Cms (9)
  • Regex (1)
  • SQL (1)
  • Uncategorized (1)
  • Videos (4)
  • vuejs (1)
  • Web Api (2)

Recent Posts

  • Commonly used regex for zip codes and addresses
  • Delete all the tables from your database
  • Orchard CMS Content Control Wrapper
  • Orchard Harvest 2017
  • Sending Emails in a Asp.net WebApi

Copyright © 2014