C# has the really powerful String.Format()
for replacing elements like {0}
with parameters. Does JavaScript have an equivalent?
This question is related to
javascript
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}');
Based on @Vlad Bezden answer 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;
};
usage:
"{greeting} {who}!".format({greeting: "Hello", who: "world"})
String.prototype.format = function(placeholders) {_x000D_
var s = this;_x000D_
for(var propertyName in placeholders) {_x000D_
var re = new RegExp('{' + propertyName + '}', 'gm');_x000D_
s = s.replace(re, placeholders[propertyName]);_x000D_
} _x000D_
return s;_x000D_
};_x000D_
_x000D_
$("#result").text("{greeting} {who}!".format({greeting: "Hello", who: "world"}));
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="result"></div>
_x000D_
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]
})
};
Source: Stackoverflow.com