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.
Answer from bformet on Stack Overflow
🌐
W3Schools
w3schools.com › jsref › jsref_replace.asp
JavaScript String replace() Method
The replace() method returns a new string with the value(s) replaced.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Template_literals
Template literals (Template strings) - JavaScript | MDN
The first argument received by the tag function is an array of strings. For any template literal, its length is equal to the number of substitutions (occurrences of ${…}) plus one, and is therefore always non-empty.
🌐
SheCodes
shecodes.io › athena › 8931-creating-a-string-with-variables-in-javascript
[JavaScript] - Creating a String With Variables in | SheCodes
Learn how to add a variable to a string using either string concatenation or string interpolation with template literals for a more modern approach. ... if I have a variable outside a function, do I need to redefine that variable inside the function? similarly, can use the same name for a variable if one is in a function? variable function scope outer variable local variable let const ... How do I make a javascript event where you click on a thumbnail image and it pops up with a full sized image?
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › String › replace
String.prototype.replace() - JavaScript | MDN
The replace() method of String values returns a new string with one, some, or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence ...
🌐
TechOnTheNet
techonthenet.com › js › string_replace.php
JavaScript: String replace() method
Let's take a look at an example of how to use the replace() method in JavaScript. The simplest way to use the replace() method is to find and replace one string with another string. This method does not involve regular expression objects. ... In this example, we have declared a variable called ...
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Substitution in JavaScript - JavaScript - The freeCodeCamp Forum
August 5, 2020 - Hi. I’ve learned how to use a variable that looks like this: var x = 3; I also know how to replace a string with another using String.replace(). That should looks like this: console.log("Hello world".replace('Hello', …
Find elsewhere
Top answer
1 of 16
214

The requirements of the original question clearly couldn't benefit from string interpolation, as it seems like it's a runtime processing of arbitrary replacement keys.

However, if you just had to do string interpolation, you can use:

const str = `My name is ${replacements.name} and my age is ${replacements.age}.`

Note the backticks delimiting the string, they are required.


For an answer suiting the particular OP's requirement, you could use String.prototype.replace() for the replacements.

The following code will handle all matches and not touch ones without a replacement (so long as your replacement values are all strings, if not, see below).

var replacements = {"%NAME%":"Mike","%AGE%":"26","%EVENT%":"20"},
    str = 'My Name is %NAME% and my age is %AGE%.';

str = str.replace(/%\w+%/g, function(all) {
   return replacements[all] || all;
});

jsFiddle.

If some of your replacements are not strings, be sure they exists in the object first. If you have a format like the example, i.e. wrapped in percentage signs, you can use the in operator to achieve this.

jsFiddle.

However, if your format doesn't have a special format, i.e. any string, and your replacements object doesn't have a null prototype, use Object.prototype.hasOwnProperty(), unless you can guarantee that none of your potential replaced substrings will clash with property names on the prototype.

jsFiddle.

Otherwise, if your replacement string was 'hasOwnProperty', you would get a resultant messed up string.

jsFiddle.


As a side note, you should be called replacements an Object, not an Array.

2 of 16
34

How about using ES6 template literals?

var a = "cat";
var b = "fat";
console.log(`my ${a} is ${b}`); //notice back-ticked string

More about template literals...

🌐
freeCodeCamp
freecodecamp.org › news › javascript-replace-how-to-use-the-string-prototype-replace-method-js-example
JavaScript Replace – How to Use the String.prototype.replace() Method JS Example
February 8, 2022 - The value to return as the replaced value may be expressed as a string or function. const variable = variable.replace("stringToReplace", "expectedString");
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Learn › JavaScript › First_steps › Strings
Handling text — strings in JavaScript - Learn web development | MDN
Template literals mostly behave the same as normal strings, but they have some special properties: You can embed JavaScript in them. You can declare template literals over multiple lines. Inside a template literal, you can wrap JavaScript variables or expressions inside ${ }, and the result will be included in the string:
🌐
Chrome Developers
developer.chrome.com › blog › getting literal with es6 template strings
Getting Literal With ES6 Template Strings | Blog | Chrome for Developers
One of their first real benefits is string substitution. Substitution allows us to take any valid JavaScript expression (including say, the addition of variables) and inside a Template Literal, the result will be output as part of the same string.
🌐
Delft Stack
delftstack.com › home › howto › javascript › javascript variable in string
How to Insert Variable Into String in JavaScript | Delft Stack
February 2, 2024 - The concept of template literals has been around for a while in JavaScript. They were earlier known as template strings. Template literals was introduced in ES6. It offers an easier way to embed variables in a given sentence than having to use cumbersome string concatenations.
🌐
Experts Exchange
experts-exchange.com › questions › 23221162 › How-to-do-variable-substitution-in-Javascript.html
Solved: How to do variable substitution in Javascript? | Experts Exchange
February 5, 2008 - The Javascript function will have before the call to the function a line like x = some string extracted from someplace and then I want the URL to be '/aaa/bbb?v=<that string>. In other words, during execution of the script I have to substitute the part on the right of the '=', with whatever is in variable ...
🌐
freeCodeCamp
freecodecamp.org › news › javascript-replace-how-to-replace-a-string-or-substring-in-js
JavaScript Replace – How to Replace a String or Substring in JS
November 7, 2024 - You may also want to replace certain characters or symbols from a string to make sure your program will work. In this article, you will learn how to use JavaScript's replace() method to replace a string or substring.
🌐
Vultr Docs
docs.vultr.com › javascript › standard-library › String › replace
JavaScript String replace() - Replace Substring | Vultr Docs
November 15, 2024 - The discussion will include basic ... by declaring a string variable containing the initial text. Use replace() to substitute a specific substring with a new one....
🌐
Coder's Block
codersblock.com › blog › javascript-string-replace-magic
JavaScript String Replace Magic / Coder's Block
This time, instead of a string for the second parameter of replace(), we’re providing a function. This function is called every time a match is found and its return value is what replaces the match. The function takes a couple parameters, though we’re only using 3 in this example.