How to Interpolate Variables in Strings in JavaScript, Without Concatenation

How can I do string interpolation in JavaScript?

Since ES6, you can use template literals:

const age = 3

console.log(`I'm ${age} years old!`)

How to interpolate variables in strings in JavaScript, without concatenation?

You can take advantage of Template Literals and use this syntax:

`String text ${expression}`

Template literals are enclosed by the back-tick (` `) (grave accent) instead of double or single quotes.

This feature has been introduced in ES2015 (ES6).

Example

var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b}.`);
// "Fifteen is 15.

How neat is that?

Bonus:

It also allows for multi-line strings in javascript without escaping, which is great for templates:

return `
<div class="${foo}">
...
</div>
`;

Browser support:

As this syntax is not supported by older browsers (mostly Internet Explorer), you may want to use Babel/Webpack to transpile your code into ES5 to ensure it will run everywhere.


Side note:

Starting from IE8+ you can use basic string formatting inside console.log:

console.log('%s is %d.', 'Fifteen', 15);
// Fifteen is 15.

Interpolate or use a variable inside a string in javascript

Combine the variable into the string properly:

 text: 'o consumo aumentou em '+qtd3+' luvas = '+qtd4+' caixas.'

How do I interpolate the value in a string variable into a constant in Perl?

Constants can be treated as subs.

{
no strict qw( refs );
push @values, $value->();
}

or

push @values, ( \&$value )->();

But that's a hackish risky approach. And the second version even hides that you are dangerously allowing the user to call any sub in any package. What I would do instead:

my %lookup;
BEGIN {
%lookup = (
STRAWBERRY => 1,
TANGERINE => 2,
PEAR => 3,
APPLE => 4,
PERSIMMON => 5,
);
}

use constant \%lookup;
push @values, $lookup{ $value };

Using this approach, inputs can be validated trivially, and invalid inputs merely result in undef.

How do I put variables inside javascript strings?

Note, from 2015 onwards, just use backticks for templating

https://stackoverflow.com/a/37245773/294884

let a = `hello ${name}`    // NOTE!!!!!!!! ` not ' or "

Note that it is a backtick, not a quote.


If you want to have something similar, you could create a function:

function parse(str) {
var args = [].slice.call(arguments, 1),
i = 0;

return str.replace(/%s/g, () => args[i++]);
}

Usage:

s = parse('hello %s, how are you doing', my_name);

This is only a simple example and does not take into account different kinds of data types (like %i, etc) or escaping of %s. But I hope it gives you some idea. I'm pretty sure there are also libraries out there which provide a function like this.



Related Topics



Leave a reply



Submit