JavaScript offers several ways to format strings, including concatenation, template literals, string interpolation, String replace(), and custom implementations like String format().
JavaScript string format example
Simple example code of several ways to format a string.
Concatenation
The +
operator is used to joining the strings and variables together.
let name = "John";
let message = "Hello " + name + ", how are you?";
console.log(message); // Output: Hello John, how are you?
Template literals
The variables are enclosed in ${}
within the backticks, and their values are automatically inserted into the string when it is evaluated.
let name = "John";
let message = `Hello ${name}, how are you?`;
console.log(message); // Output: Hello John, how are you?
String interpolation
The variables are enclosed in ${}
within the string, but we need to use eval()
to evaluate the string and replace the variables with their values.
let name = "John";
let message = "Hello ${name}, how are you?";
console.log(eval('`' + message + '`')); // Output: Hello John, how are you?
String.replace()
We use String.replace()
to replace placeholders in the message
string with the values of the name
and age
variables.
let name = "John";
let message = "Hello {name}, how are you?".replace('{name}', name);
console.log(message); // Output: Hello John, how are you?
String.format() (custom implementation):
<!DOCTYPE html>
<html>
<head>
<script>
String.prototype.format = function() {
let formatted = this;
for (let i = 0; i < arguments.length; i++) {
formatted = formatted.replace(`{${i}}`, arguments[i]);
}
return formatted;
};
let name = "John";
let message = "Hello {0}, how are you?".format(name);
console.log(message);
</script>
</head>
<body>
</body>
</html>
Output:
Do comment if you have any doubts or suggestions on this JS string topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version