Add a String to beginning and end of Another String in JS

avatar

Borislav Hadzhiev

Wed Nov 17 20211 min read

banner

Photo by Omar Ram

Add a String to beginning and end of Another String #

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

index.js
const str = 'ello worl'; const result = 'h' + str + 'd'; // 👇️ "hello world" console.log(result);

We used the addition operator to add a string to the beginning and end of another string.

When used with strings, the addition operator concatenates them, and when used with numbers, the operator sums the numbers.

index.js
console.log('ab' + 'cd'); // 👉️ "abcd" console.log(2 + 2); // 👉️ 4

You could achieve the same result, using a template literal.

index.js
const str = 'ello worl'; const result = `h${str}d`; // 👇️ "hello world" console.log(result);

We wrapped the string using backticks, which makes it a template literal.

The dollar sign and curly braces part ${} is an expression that gets evaluated. In our case the value of the str variable replaces the ${str} part of the template literal.

Which approach you pick is a matter of personal preference. I'd go with the addition (+) operator, as I find it easier to read and more intuitive, especially for developers who are not familiar with template literals.
Use the search field on my Home Page to filter through my more than 1,000 articles.