String Interpolation in JavaScript
These are the following ways to interpolate the given strings:
1. Template Literals (ES6)
Template literals are the most modern and preferred method for string interpolation in JavaScript. They use backticks (`` ` ``) and ${} syntax to embed expressions.
const n = "Alice";
const res = `Hello, ${n}!`;
console.log(res);
const n = "Alice";
const res = `Hello, ${n}!`;
console.log(res);
Output
Hello, Alice!
2. String Concatenation (Before ES6)
Before ES6, string interpolation was achieved using the + operator to concatenate strings and variables.
const n = "Alice";
const res = "Hello, " + n + "!";
console.log(res);
const n = "Alice";
const res = "Hello, " + n + "!";
console.log(res);
Output
Hello, Alice!
3. Using String.concat() Method
The String.concat() method can also be used for string concatenation, though it's less commonly used for interpolation.
const n = "Alice";
const res = "Hello, ".concat(n, "!");
console.log(res);
const n = "Alice";
const res = "Hello, ".concat(n, "!");
console.log(res);
Output
Hello, Alice!
4. Array Join() Method
You can use an array and the join() method to interpolate strings, though this is less common and more verbose.
const n = "Alice";
const res = ["Hello, ", n, "!"].join("");
console.log(res);
const n = "Alice";
const res = ["Hello, ", n, "!"].join("");
console.log(res);
Output
Hello, Alice!
5. Using a Custom Function
A custom function can be used to handle string interpolation, especially if the string structure is complex or repeated.
function interpolate(t, v) {
return t.replace(/\${(.*?)}/g, (match, p1) => v[p1.trim()]);
}
const n = "Alice";
const t = "Hello, ${ n }!";
const res = interpolate(t, { n });
console.log(res);
function interpolate(t, v) {
return t.replace(/\${(.*?)}/g, (match, p1) => v[p1.trim()]);
}
const n = "Alice";
const t = "Hello, ${ n }!";
const res = interpolate(t, { n });
console.log(res);
Output
Hello, Alice!
6. Tagged Template Literals
Tagged template literals allow you to parse template literals with a function.
function tag(s, ...v) {
return s.raw[0] + v.join("");
}
const n = "Alice";
const res = tag`Hello, ${n}!`;
console.log(res);
function tag(s, v) {
return s.raw[0] + v.join("");
}
const n = "Alice";
const res = tag`Hello, ${n}!`;
console.log(res);
Output
Hello, Alice