JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to prepend a string to the beginning of a string in JavaScript?

Using the addition operator (+) or template literal, you can add a string to the beginning of a string. You already know that the addition operator is a binary operator, so when both operands are numbers, then it performs summation. On the other hand, if one of the operands is a string, it performs concatenation.

let str = "Mohit";

console.log("Hello " + str); //Hello Mohit
console.log("Hello " + "World"); //Hello World
console.log("Hello" + 123); //Hello123
console.log(12 + 13); //25

Template literal is a new feature introduced in ES6. In template literal, you use backticks instead of single or double quotation marks. It is the easiest way to prepend a string to the beginning of a string. Also, within the template literal, you use a dollar sign and curly braces to write an expression.

let str = "Mohit";

let result = `Hello ${str}`; //Hello Mohit
console.log(result);

Recommended Posts