Vivek S
Vivek S

Reputation: 5550

JS string formatting operation - substitute a variable value to string

In python & other programming languages there's a way to substitute a variable's value in between a string easily, like this,

name="python"
a="My name is %s"%name
print a
>>>My name is python

How do I achieve this in java-script? The plain old string concatenation is very complex for a large string.

Upvotes: 8

Views: 15304

Answers (5)

y4suyuki
y4suyuki

Reputation: 380

It's 2017, we have template literals.

var name = "javascript";
console.log(`My name is ${name}`);
// My name is javascript

It uses back-tick not single quote.

You may find this question and answers also useful. JavaScript equivalent to printf/string.format

Upvotes: 24

terryp
terryp

Reputation: 249

Using Node, this should work.

[terryp@boxcar] ~  :: node
> var str = 'string substitute!';
> console.log('This is a %s', str);
This is a string substitute!
>

Upvotes: 0

redexp
redexp

Reputation: 5075

Another way is using CoffeeScript. They have sugar like in ruby

name = "javascript"
a = "My name is #{name}"
console.log a
# >>> My name is javascript

Upvotes: 2

zura
zura

Reputation: 106

This is not possible in javascript, so the only way to achieve this is concatenation. Also another way could be replacing particular values with regexp.

Upvotes: 0

Sandro Munda
Sandro Munda

Reputation: 41070

There's no native way to do that. In javascript, you do:

var name = 'javascript';
var a = 'My name is ' + name;
console.log(a);

>>>My name is javascript

Otherwise, if you really would like to use a string formatter, you could use a library. For example, https://github.com/alexei/sprintf.js

With sprintf library:

var name = 'javascript';
sprintf('My name is %s', name);

>>>My name is javascript

Upvotes: 5

Related Questions