How to Insert Variables in JavaScript Strings

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.

How to insert variables in JavaScript strings?

Introduced in ES6 as "template strings"

MDN docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

const name = "Nick"
const greeting = `Hello ${name}` // "Hello Nick"

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.

How an I insert variables at a specific place in a string?

You can use ES2015 template literals. But, the variables should be defined before using them.

var name1 = "Phil";var name2 = "Amy";var templateString = `Hello ${name1}, my name is ${name2}`;
console.log(templateString);document.body.innerHTML = templateString;

Insert variable into imported string

Instead of exporting a string (defined with a template literal), export a function which takes a parameter, which is then interpolated into a returned template literal:

export const makeGreeting = name => `Hello, ${name}`;

and

import { makeGreeting } from './const';
makeGreeting('barry');

Also, def displayGreeting(name) { is not valid Javascript - declare functions with function, or () =>, or something of the sort.

Adding a string variable inside an html code

In your case, your dataType variable should be defined before you will use that variable in your string literal (template):

var dataType = 'HELLO';
var htmlBlock = `<div class="icon negative big toleft" id="cancel-btn"><i class="fas fa-minus-circle"></i></div>
<div class="icon add big toleft"><i class="fas fa-check-circle"></i></div>
<input type="text" class="contact-input" style="margin-bottom: 5px;" maxlength="50" name="my-contact-phone" data-name="Name" placeholder="${dataType}">`;

console.log(htmlBlock);

UPDATED:

in this case you could do:

var getHtmlBlock = function(dataType) {
return `<div class="icon negative big toleft" id="cancel-btn"><i class="fas fa-minus-circle"></i></div><div class="icon add big toleft"><i class="fas fa-check-circle"></i></div><input type="text" class="contact-input" style="margin-bottom: 5px;" maxlength="50" name="my-contact-phone" data-name="Name" placeholder="${dataType}">`;
};

var myDataType = getHtmlBlock('Add your number');
console.log(myDataType); // replaced string with argument value;

Put your string into function, and replace ${dataType} by passing as argument.

How can I add a variable to console.log?

Then use + to combine strings:

console.log("story " + name + " story");

Insert variables inside another string variable in Javascript

You need to use the same type of quote to close and reopen the string.

var api= "http://api.openweathermap.org/data/2.5/weather?lat="+lat+"&lon="+long+"&appid=c873adc18574701f4fb0abe01d927819";

How to insert multiple variables into a string?

You can use Template literals (Template strings)

Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. They were called "template strings" in prior editions of the ES2015 specification.

var adjective1 = 'amazing';var adjective2 = 'fun';var adjective3 = 'entertaining';
var madLib = `The Intro to JavaScript course is ${adjective1}. James and Julia are so ${adjective2}. I cannot wait to work through the rest of this ${adjective3} content!`;console.log(madLib);


Related Topics



Leave a reply



Submit