by
2
6
476k
8
Top 1% !
Popular
Pearl of Wisdom
Tagged
Specified
MultiPlatform
Popularity: 1493rd place
Languagejavascript
LicenseMIT_X11

JavaScript equivalent to C# String.format

The code below is the Javascript equivalent to C# String.Format() for replacing elements like {0}, {1}, {2} with parameters.

In this case the String prototype is modified, adding the new format() method to all string instances.

How to use

var mystring = "Hello {0}, how are you? My name is {1}. Bye {0}!"
mystring.format("Alice", "Bob")
// Output
// Hello Alice, how are you? My name is Bob. Bye Alice!

Original link:
http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/238253/JavaScript-equivalent-to-C--String-forma?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
// First, checks if it isn't implemented yet. if (!String.prototype.format) { String.prototype.format = function() { var args = arguments; return this.replace(/{(\d+)}/g, function(match, number) { return typeof args[number] != 'undefined' ? args[number] : match ; }); }; }
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus