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
JavaScript Object Bracket Notation ({ Navigation } =) on Left Side of Assign
How to Pass a Parameter to a Settimeout() Callback
When Should I Use Arrow Functions in Ecmascript 6
How to Use Unicode-Aware Regular Expressions in JavaScript
What Does "Use Strict" Do in JavaScript, and What Is the Reasoning Behind It
What Is the Use of the JavaScript 'Bind' Method
Escape String For Use in JavaScript Regex
How to Use Formdata For Ajax File Upload
Facebook Js Sdk'S Fb.API('/Me') Method Doesn't Return the Fields I Expect in Graph API V2.4+
Uploading Both Data and Files in One Form Using Ajax
Reactjs Component Names Must Begin With Capital Letters
Programmatically Navigate Using React-Router
JavaScript Window Resize Event
How to Add 1 Day to Current Date
How to Get the Full Object in Node.Js'S Console.Log(), Rather Than '[Object]'
Fastest Way to Duplicate an Array in JavaScript - Slice Vs. 'For' Loop