6

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.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
Vivek S
  • 5,384
  • 8
  • 51
  • 72
  • 2
    possible duplicate of [String.Format in javascript?](http://stackoverflow.com/questions/2534803/string-format-in-javascript) – CodingIntrigue Oct 01 '13 at 07:12

5 Answers5

23

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

Community
  • 1
  • 1
y4suyuki
  • 361
  • 3
  • 7
4

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
Sandro Munda
  • 39,921
  • 24
  • 98
  • 123
  • console.log does string formatting/substitution. var myobject = {foo:'bar',x: 'y'}; console.log("myobject = %o", myobject); console.log("foo = %s", myobject.foo); – keith73 Mar 25 '14 at 18:20
2

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
redexp
  • 4,765
  • 7
  • 25
  • 37
0

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.

zura
  • 106
  • 6
0

Using Node, this should work.

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