Append a String to the End of another String in JS

avatar

Borislav Hadzhiev

Wed Nov 17 20211 min read

Append a String to the End of another String #

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

index.js
const str = 'one '; const result = str + 'two'; console.log(result); // ๐Ÿ‘‰๏ธ "one two"

We used the addition operator to append a string to the end 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(3 + 3); // ๐Ÿ‘‰๏ธ 6

An alternative approach is to use the String.concat method.

Use the concat() method to append a string to the end of another string, e.g. str.concat("after"). The concat method concatenates the supplied parameters to the string and the combined text.

index.js
const str = 'one '; const result = str.concat('two'); console.log(result); // ๐Ÿ‘‰๏ธ "one two"

The concat method takes one or more strings as parameters and concatenates them to the string on which it was called.

index.js
const result = 'one '.concat('two', ' three'); console.log(result); // ๐Ÿ‘‰๏ธ "one two three"

The method returns a new string containing the combined text.

Alternatively, you could use a template literal.

index.js
const str = 'one '; const result = `${str}two`; console.log(result); // ๐Ÿ‘‰๏ธ "one two"

The dollar sign curly braces ${} part is an expression that gets evaluated.

In the example, the value of the str variable replaces the ${} part.

Which of the three approaches you pick, is a matter of personal preference. I'd go with the addition (+) operator, as I find it the most intuitive and direct solution.

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