8

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.

1

5 Answers 5

24

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

Sign up to request clarification or add additional context in comments.

2 Comments

It should be accepted answer, but the question was asked 5 years ago.
I love this answer, but we unfortunately live in a world a ton of pre-ES6 code out there, and this is ES6 and beyond, no?
5

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

1 Comment

console.log does string formatting/substitution. var myobject = {foo:'bar',x: 'y'}; console.log("myobject = %o", myobject); console.log("foo = %s", myobject.foo);
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

Comments

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.

Comments

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!
>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.