Home >Web Front-end >JS Tutorial >How do I concatenate strings with variables in JavaScript?
Concatenating Strings with Variables
Attempting to concatenate a string and a variable often arises when manipulating elements in a web page. To achieve this in JavaScript, there are several approaches.
Method 1: String Concatenation
The most straightforward method is to simply concatenate the string with the variable using the plus operator ( ). For example:
let id = 42; let str = 'horseThumb' + id; // str will be "horseThumb42"
Method 2: Template Literals (ES6)
Template literals (also known as template strings) introduced in ECMAScript 2015 offer a concise and readable syntax for string interpolation. To use this method, enclose the string in backticks (`) and embed the variable within the string using ${}.
let id = 42; let str = `horseThumb${id}`; // str will be "horseThumb42"
Troubleshooting
If you encounter issues concatenating strings with variables, consider the following potential reasons:
The above is the detailed content of How do I concatenate strings with variables in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!