nehem
nehem

Reputation: 13642

JavaScript equivalent of Python's parameterised string.format() function

Here is the Python example

>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')

'Coordinates: 37.24N, -115.81W'

I am looking for a way to emulate this behavior in JavaScript. As I have plenty of templates strings as """{} lorem {} ipsum""" and bunch of JSON objects as k,v pairs that correspond to parameters & values.

I hate to implement my own parser if something equivalent already exist. Any similar libraries would be much appreciated.

Upvotes: 2

Views: 2296

Answers (1)

joed4no
joed4no

Reputation: 1363

In JavaScript this is called Template Literals. You can read about it here. It works similar to the Python format function but its done inline.

`string text ${some_variable} string text`

Where the ` back tick starts and ends the string. Inside the back ticks any ${variable} will be converted to the value of the variable. Just make sure the variable is in the scope of the string you are trying to format.

Upvotes: 5

Related Questions