Last updated: Mar 4, 2024
Reading timeยท2 min
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.
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.
console.log('ab' + 'cd'); // ๐๏ธ "abcd" console.log(2 + 2); // ๐๏ธ 4
You could achieve the same result by using a template literal
.
You can also use a template literal to add a string to the beginning and end of another string.
Template literals allow us to embed expressions into a string.
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.
Alternatively, you can use the String.join()
method.
Array.join()
This is a two-step process:
Array.join()
method to join the strings without a separator.const prefix = 'h'; const suffix = 'd'; const str = 'ello worl'; const result = [prefix, str, suffix].join(''); console.log(result); // ๐๏ธ hello world
We wrapped the strings in an array to be able to use the Array.join()
method.
The Array.join() method concatenates all of the elements in an array using a separator.
The only argument the Array.join()
method takes is a separator
- the string
used to separate the elements of the array.
separator
argument is set to an empty string, the array elements are joined without any characters in between them.If you only need to append a string to another string, you can also use the
String.concat()
method.
The concat
method concatenates the supplied parameters to the string.
const str = 'bobby '; const result = str.concat('hadz'); console.log(result); // ๐๏ธ "bobby hadz"
The String.concat() method takes one or more strings as parameters and concatenates them to the string on which it was called.
const result = 'one '.concat('two', ' three'); console.log(result); // ๐๏ธ "one two three"
The method returns a new string containing the combined text.