Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's %s equivalent in Javascript?

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

like image 992
Dan Monero Avatar asked Jun 26 '26 22:06

Dan Monero


2 Answers

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))
like image 132
brk Avatar answered Jun 28 '26 13:06

brk


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.

like image 31
ngChaitanya Avatar answered Jun 28 '26 11:06

ngChaitanya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!