How to Do String Interpolation in JavaScript

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 make string interpolation in javascript?

You can use template literals by using ` (sorry, can't put it in block code) instead of " or ':

let name = "world";
console.log("Hello, " + name); // Classical way
console.log(`Hello, ${name}`); // With template literals

How to perform string interpolation in TypeScript?

In JavaScript you can use template literals:

Template literals are literals delimited with backticks (`)

let value = 100;
console.log(`The size is ${ value }`);

String interpolation of a string stored in a variable

I use a little helper function that let's you use straight es6 string interpolation in a round about way:

const template= (template, ctx) => {
const script = new vm.Script('`' + template + '`')
return script.runInNewContext(ctx)
}

const results = template('hello ${foo}', {foo:'jane'})

But, if you just need to do do a simple interpolation, why not just export the sql as a function?

const queryFromFile1 = str => (`SELECT * Name FROM Contact WHERE Name = ${str}`)

const query = queryFromFile1('Jane')

How can I avoid control character interpretation in Javascript template string interpolation?

You could remove the double quotes, and use JSON.stringify which also produces those quotes, and which encodes newline characters (and more, such as TAB, BS, FF, and escapes double quote and backslash):

let nl = "\r\n";
console.log(`Using ${JSON.stringify(nl)} as newline`);

// Or with a newline in a template literal:

nl = `
`;
console.log(`Using ${JSON.stringify(nl)} as newline`);

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.

array of strings with string interpolation

Convert the array to a string using JSON.stringify():

const array = ["string1", "string2", "string3"];

const total = 10000;

const url = `http://localhost:8080/total=${total}&array=${JSON.stringify(array)}`

console.log(url)


Related Topics



Leave a reply



Submit