Home >Web Front-end >JS Tutorial >How do I concatenate a string with a variable in JavaScript to create a new string?
Concatenating Strings with Variables in JavaScript
In JavaScript, concatenating a string with a variable requires specific syntax. This tutorial addresses the common question of how to combine a string and a numeric variable to create a new string.
Original Question:
The user wishes to create a string by combining a string, "horseThumb," and a passed numeric variable, "id," but faces difficulties.
Answer and Troubleshooting:
The code provided in the question is correct. However, there could be other issues affecting the desired outcome.
Using Template Literals:
Since ECMAScript 2015, template literals (template strings) offer an alternative method for concatenation:
document.getElementById(`horseThumb_${id}`).className = "hand positionLeft";
Debugging Assistance:
To identify the source of the problem, add these lines to the beginning of the function:
alert('ID number: ' + id); alert('Return value of gEBI: ' + document.getElementById('horseThumb_' + id));
These pop-up windows will provide information regarding the passed ID and the element's existence.
The above is the detailed content of How do I concatenate a string with a variable in JavaScript to create a new string?. For more information, please follow other related articles on the PHP Chinese website!