Skip to main content

How To Add A Variable Inside A String In JavaScript

How-To-Add-A-Variable-Inside-A-String-In-Javascript

How To Add A Variable Inside A String In JavaScript

When working with strings in JavaScript, there are situations where we need to include variable values dynamically within the text. This allows us to create personalized and dynamic messages or output.

In this article, we will explore three methods for adding a variable inside a string in JavaScript. Whether you prefer concatenation with the + operator, the readability and convenience of template literals in modern JavaScript, or the traditional approach of string interpolation with the replace() function, each method offers a way to incorporate variables seamlessly into strings. By understanding these techniques, you will gain the flexibility to generate dynamic and customized text, opening up possibilities for enhanced user experiences and data presentation. So let's dive in and discover how to effortlessly include variables within strings in JavaScript.


01. Using Concatenation Operator (+)

var name = "Rustcode";
var greeting = "Hello, " + name + "!";

console.log(greeting);

Output:

"Hello, Rustcode!"

In this method, we use the concatenation operator (+) to combine the string "Hello, " with the value of the name variable. The resulting string is stored in the greeting variable. The console.log() statement outputs the final greeting, which would be "Hello, John!" in this case.



02. Using Template Literals (ES6+)

var name = "Rustcode";
var greeting = `Hello, ${name}!`;

console.log(greeting);

Output:

"Hello, Rustcode!"

With template literals, denoted by backticks (), we can include variables directly inside the string using ${}syntax. Thenamevariable is enclosed within ${} to create a placeholder that is replaced with the actual value. The resulting string is assigned to the greeting variable. The console.log()` statement outputs the final greeting, which would be "Hello, Rustcode!" in this example. Template literals offer a more readable and concise way to add variables inside strings.



03. Using String Interpolation (ES5 and earlier)

var name = "Rstcode";
var greeting = "Hello, %s!".replace("%s", name);

console.log(greeting);

Output:

"Hello, Rustcode!"

In this method, we utilize the replace() function to replace a placeholder ("%s") in the string with the value of the name variable. The resulting string is stored in the greeting variable. The console.log() statement outputs the final greeting, which would be "Hello, John!" in this case. While this method works in older versions of JavaScript, it is less commonly used compared to the concatenation operator or template literals.


Comments