In JavaScript, you can use string interpolation to format a string with variables. One way to do this is to use template literals, which were introduced in ECMAScript 6.
Using template literals to format a string with variables:
const name = 'John';
const age = 30;
const message = `My name is ${name} and I'm ${age} years old.`;
console.log(message); // Output: "My name is John and I'm 30 years old."
If you’re working with older versions of JavaScript that don’t support template literals, you can use the String.prototype.replace()
method to replace placeholders in a string with values:
const name = 'John';
const age = 30;
const message = 'My name is {0} and I\'m {1} years old.'.replace('{0}', name).replace('{1}', age);
console.log(message); // Output: "My name is John and I'm 30 years old."
JavaScript string format {0} example
A simple example code uses the String.prototype.replace()
method.
<!DOCTYPE html>
<html>
<head>
<script>
let name = "John";
let age = 30;
let message = "My name is {0} and I'm {1} years old.";
message = message.replace("{0}", name);
message = message.replace("{1}", age);
console.log(message);
</script>
</head>
<body>
</body>
</html>
Output:
In this example, the string message
contains placeholders {0}
and {1}
that will be replaced with the values of the variables name
and age
, respectively.
Do comment if you have any doubts or suggestions on this JS string format topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version