3

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

Dan Monero
  • 417
  • 5
  • 12
  • [Template_literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) – charlietfl May 28 '18 at 17:07
  • `s => \`Hello ${s}, how are you?\`` – ASDFGerte May 28 '18 at 17:07
  • the only way (that I know) to do that is with a function that takes a parameter and return an object (in this case with the name that you want pass in as an argument) – manAbl May 28 '18 at 17:07
  • @ASDFGerte Thanks, but I want to save this JSON as separated file.. – Dan Monero May 28 '18 at 17:12
  • seems like just syntactic sugar for `j['dynamicText'].replace('s%', 'Dan')` – Slai May 28 '18 at 17:13
  • Possible duplicate of [NodeJS String format like Python?](https://stackoverflow.com/questions/10788408/nodejs-string-format-like-python) – Frax May 28 '18 at 17:17

5 Answers5

4

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))
brk
  • 48,835
  • 10
  • 56
  • 78
4

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.

ngChaitanya
  • 435
  • 2
  • 8
  • In Node there is [`util.format()`](https://nodejs.org/api/util.html#util_util_format_format_args), so your answer is quite inaccurate, even though it's correct for in-browser JS. – Frax May 28 '18 at 17:20
  • Yes agree there is .format in nodeJs but could you let me know why would this is inaccurate for node? you mean this would break in NodeJs? – ngChaitanya May 28 '18 at 17:25
  • My comment was aimed at "There is no predefined way in JavaScript" sentence, as there is a predefined way in Node. Your code would work just the same, but would be kind of reinventing the wheel in this case. – Frax May 28 '18 at 17:47
1

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;
    });
}
gtsiam
  • 85
  • 10
0

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.

Haroldo_OK
  • 6,612
  • 3
  • 43
  • 80
0

I've found a great npm module that does exactly what I was needed - string-format.

String-Format in NPM

Dan Monero
  • 417
  • 5
  • 12