Prepend a String to the Beginning of Another String in JS

avatar

Borislav Hadzhiev

Wed Nov 17 20211 min read

Prepend a String to the Beginning of Another String #

Use the addition (+) operator to prepend a string to the beginning of another string, e.g. "example" + str. When used with strings, the addition operator concatenates the strings and returns the result.

index.js
const str = 'world'; const result = 'hello ' + str; // ๐Ÿ‘‡๏ธ "hello world" console.log(result);

We used the addition operator to prepend a string to the beginning of another string.

When used with strings, the addition (+) operator concatenates them. When used with numbers, it sums them.

index.js
console.log('hello ' + 'world'); // ๐Ÿ‘‰๏ธ "hello world" console.log(5 + 5); // ๐Ÿ‘‰๏ธ 10

An alternative approach is to use a template literal.

To prepend a string to the beginning of another string, use a template literal, e.g. hello ${str}. The dollar sign and curly braces part is an expression that gets evaluated.

index.js
const str = 'world'; // template literal const result = `hello ${str}`; // ๐Ÿ‘‡๏ธ "hello world" console.log(result);

Template literals allow us to use expressions ${}. In the example, the ${str} part gets replaced with the value of the str variable.

This achieves the same result as using the addition operator, however in my opinion it's a bit of an overkill in this scenario.

The addition (+) operator is more direct and easier to read.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee