Javascript concatenate string and variable
Javascript concatenate string and variable:In JavaScript ES6, you can concatenate strings and variables using template literals. Template literals are enclosed in backticks () instead of single or double quotes. To include a variable, use the
${variableName}` syntax within the template literal.




Thanks for your feedback!
Your contributions will help us to improve service.
How can you concatenate a string and a variable in JavaScript?
In the given example, JavaScript is used to concatenate a string and variables to create a dynamic message. The variables include name
with the value "John", age
with the value 25, and profession
with the value "web developer". The message is constructed using template literals enclosed in backticks (
), allowing variables to be inserted directly using ${}
syntax. The resulting message is assigned to the message
variable.
Finally, JavaScript accesses the HTML element with the ID "output" using document.getElementById()
and sets its innerHTML
to the value of the message
variable, effectively displaying the dynamic message on the web page.
Javascript concatenate string and variable Example
xxxxxxxxxx
<div id="app">
<p id="output"></p>
</div>
<script>
window.onload = function () {
var name = "John";
var age = 25;
var profession = "web developer";
var message = `Hello, <span class="highlight">${name}</span>!
You are <span class="highlight">${age}</span> years old
and work as a <span class="highlight">${profession}</span>.`;
// Access the paragraph element with the ID "output" and set its innerHTML to the message
document.getElementById("output").innerHTML = message;
}
</script>