Reputation: 437
I'm currently learning NodeJS after working with Python for the last few years.
In Python I was able to save a string inside a JSON with dynamic parameters and set them once the string loaded, for example:
MY JSON:
j = {
"dynamicText": "Hello %s, how are you?"
}
and then use my string like that:
print(j['dynamicText'] % ("Dan"))
so Python replaces the %s
with "Dan
".
I am looking for the JS equivalent but could not find one. Any ideas?
** Forgot to mention: I want to save the JSON as another config file so literals won't work here
Upvotes: 3
Views: 2804
Reputation: 437
I've found a great npm module that does exactly what I was needed - string-format
.
Upvotes: 0
Reputation: 87
You can write a String.format method, using regex, and the String.replace method:
String.prototype.format = function() {
var args = arguments;
return this.replace(/{(\d+)}/g, (match, p1) => {
var i = parseInt(p1);
return typeof args[i] != 'undefined' ? args[i] : match;
});
}
After that, running:
console.log("{0}{1}".format("John", "Doe"));
Will output: John Doe
Of course, if you don't like editing the prototype of objects you don't own (it is generally good practice), you can just create a function:
var format = function(str) {
var args = arguments;
return str.replace(/{(\d+)}/g, (match, p1) => {
var i = parseInt(p1);
return typeof args[i+1] != 'undefined' ? args[i+1] : match;
});
}
Upvotes: 1
Reputation: 7260
For a few nice alternatives, you may want to take a look at JavaScript equivalent to printf/string.format
While it's asking for a C-like printf()
equivalent for JS, the answers would also apply to your question, since Python format strings are inspired by C.
Upvotes: 0
Reputation: 435
There is no predefined way in JavaScript, but you could still achieve something like below. Which I have done in my existing Application.
function formatString(str, ...params) {
for (let i = 0; i < params.length; i++) {
var reg = new RegExp("\\{" + i + "\\}", "gm");
str = str.replace(reg, params[i]);
}
return str;
}
now formatString('You have {0} cars and {1} bikes', 'two', 'three')
returns 'You have two cars and three bikes'
In this way if {0} repeats in String it replaces all.
like formatString('You have {0} cars, {1} bikes and {0} jeeps', 'two', 'three')
to "You have two cars, three bikes and two jeeps"
Hope this helps.
Upvotes: 4
Reputation: 50326
Use template literal. This is comparatively new and may not support ancient browsers
var test = "Dan"
var j = {
"dynamicText": `Hello ${test}, how are you?`
}
console.log(j["dynamicText"])
Alternatively you can create a function and inside that function use string.replace
method to to replace a word with new word
var test = "Dan"
var j = {
"dynamicText": "Hello %s, how are you?"
}
function replace(toReplaceText, replaceWith) {
let objText = j["dynamicText"].replace(toReplaceText, replaceWith);
return objText;
}
console.log(replace('%s', test))
Upvotes: 4