JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to add a string to the beginning and end of a string in JavaScript?

Using the addition operator (+), you can add a string to the beginning and end of a string. The addition operator (+) is a binary operator. When one of the operands is a string, then the addition operator concatenates the string.

On the other hand, when both operands are numbers, then the addition operator sums the numbers.

let str = "Mohit";

let result = "Hello " + str + ", How are you?";

console.log(result); //"Hello Mohit, How are you?"
console.log("Java" + "Script"); //"JavaScript"
console.log("Username:" + 123); //"Username:123"
console.log(3 + 5); //8

You can also add a string to the beginning and end of a string using template literal. In template literal, the string is enclosed within backticks. It uses the dollar sign and curly braces (${}) as a placeholder to evaluate the variables.

Let's rewrite the same code using template literal.

let str = "Mohit";

let result = `Hello ${str}, How are you?`;

console.log(result); //"Hello Mohit, How are you?"

Recommended Posts