Append a number to a string in JavaScript
This post will discuss how to append a number to a string in JavaScript.
There are several methods to append a number to a string object in JavaScript. Here are some of the most common functions, along with some examples:
1. Using + or += operator
We can use the + operator to concatenate a number and a string. This operator converts the operands to strings if they are not already strings, and then joins them together. We can use this operator to append a number to a string by passing them as operands and converting the integer to a string implicitly. Here’s an example:
|
1 2 3 4 5 6 7 8 |
let str = "The result is "; let num = 42; let result = str + num; console.log(result); // "The result is 42" str += num; console.log(str); // "The result is 42" |
2. Using String.concat() function
Another way is to use the String.concat() function, which returns a new string that is the result of joining two or more strings. However, using the + operator is less error prone in case the first operand is not a string. Here’s an example:
|
1 2 3 4 5 6 7 |
let str = "The result is "; let num = 42; // Concatenate the string and the integer using concat let result = str.concat(num); console.log(result); // "The result is 42" |
3. Using template literals
Template literals are strings that allow embedded expressions and multi-line strings. We can use the template literals syntax to create a string that interpolates a number using the ${} notation. This syntax allows us to embed expressions inside a string literal, which is enclosed by backticks (`). For example, to append a number to a string, we can write:
|
1 2 3 4 5 6 |
let str = "The result is "; let num = 42; let result = `${str}${num}`; console.log(result); // "The result is 42" |
That’s all about appending a number to a string in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)