Is there a C # String.Format () equivalent in JavaScript?

C # has a really powerful String.Format() for replacing elements like {0} with parameters. Does JavaScript have an equivalent?

+67
javascript
Aug 23 '13 at 14:47
source share
4 answers

Try sprintf () for javascript .

or

 // 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 ; }); }; } "{0} is dead, but {1} is alive! {0} {2}".format("ASP", "ASP.NET") 

Both answers are torn from the JavaScript equivalent for printf / string.format

+71
Aug 23 '13 at 14:49
source share

I use:

 String.prototype.format = function() { var s = this, i = arguments.length; while (i--) { s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]); } return s; }; 

usage: "Hello {0}".format("World");

I found it in String.format Equivalent in jQuery

UPDATED:

In ES6 / ES2015 you can use string templating for example

 'use strict'; let firstName = 'John', lastName = 'Smith'; console.log(`Full Name is ${firstName} ${lastName}`); // or console.log(`Full Name is ${firstName + ' ' + lastName}'); 
+29
Feb 18
source share

I created it a long time ago related question

 String.Format = function (b) { var a = arguments; return b.replace(/(\{\{\d\}\}|\{\d\})/g, function (b) { if (b.substring(0, 2) == "{{") return b; var c = parseInt(b.match(/\d/)[0]); return a[c + 1] }) }; 
+12
Aug 23 '13 at 14:54
source share

Based on @ Vlad Abyss , I use this slightly modified code because I prefer named placeholders:

 String.prototype.format = function(placeholders) { var s = this; for(var propertyName in placeholders) { var re = new RegExp('{' + propertyName + '}', 'gm'); s = s.replace(re, placeholders[propertyName]); } return s; }; 

using:

 "{greeting} {who}!".format({greeting: "Hello", who: "world"}) 

 String.prototype.format = function(placeholders) { var s = this; for(var propertyName in placeholders) { var re = new RegExp('{' + propertyName + '}', 'gm'); s = s.replace(re, placeholders[propertyName]); } return s; }; $("#result").text("{greeting} {who}!".format({greeting: "Hello", who: "world"})); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="result"></div> 
+10
Nov 01 '14 at 11:58
source share



All Articles