Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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

like image 785
David Thielen Avatar asked Aug 23 '13 14:08

David Thielen


People also ask

Why is there a slash in AC?

Senior Member. You read it as "ei-cee" (no "slash" pronounced). In terms of distinguishing between "air conditioning" and "air conditioner," I can think of an example like "Today, I bought a new air conditioner" ("conditioning" not allowed). I personally would not say "Today, I bought a new AC."

Why is it called AC?

Air conditioning, often abbreviated as A/C or AC, is the process of removing heat from an enclosed space to achieve a more comfortable interior environment (sometimes referred to as 'comfort cooling') and in some cases also strictly controlling the humidity of internal air.

What is meant by AC?

a/ c is an abbreviation for air-conditioning. Keep your windows up and the a/c on high.


2 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 pulled from JavaScript equivalent to printf/string.format

like image 107
Scott Avatar answered Sep 20 '22 20:09

Scott


I am using:

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 at Equivalent of String.format in JQuery

UPDATED:

In ES6/ES2015 you can use string templating for instance

'use strict';  let firstName = 'John',     lastName = 'Smith';  console.log(`Full Name is ${firstName} ${lastName}`);  // or console.log(`Full Name is ${firstName + ' ' + lastName}'); 
like image 28
Vlad Bezden Avatar answered Sep 19 '22 20:09

Vlad Bezden