How to Combine Multiple Strings with JavaScript

Image for post
Image for post
Photo by 🇨🇭 Claudio Schwarz | @purzlbaum on Unsplash

Combining strings is something that we have to do often with JavaScript.

In this article, we’ll look at how to combine them with JavaScript.

Plus Operator

The + operator also lets us combine multiple strings together.

For instance, we can write:

This is uglier than the other solutions since we have to use the + sign for each string expression.

Mutative Concatenation

We can concatenate to existing strings.

For instance, we can write:

Then we concatenate to the greeting string.

We can’t use const to declare greeting since we’re assigning a new value to it.

Template Literals

Template literals are a newer string type that lets us interpolate expressions into them,.

For instance, we can write:

We have the firstName and lastName variables.

Then we get 'hi james smith’ as the value of`greeting .

And we interpolated them into the string expression.

The ${...} is the interpolation symbol.

We can put any expression in between them.

Now we don’t have to worry about looking at ugly concatenation strings.

Array.prototype.join()

Array instances have the join method.

It takes an optional separation to combine the strings with.

If the array entries aren’t strings, then they’ll be coerced to strings.

For instance, we can use it by writing:

We join 'hi' , firstName and lastName with a space string.

And we get the same result as with the previous example.

The separator can be any string.

String.prototype.concat()

Strings have the concat method to let us concatenate various strings into one.

For instance, we can write:

We have the concat method which has all the strings that we want to join together.

They’re 'hi' , firstName , and lastName with empty spaces in between each of them.

So we get the same result as before.

Escaping Quotes

If we want to use single quotes in single-quoted strings, double quotes with double-quotes strings, and backticks in template literals, then we’ve to escape those characters in those strings.

We can do that with a \ character.

For instance, we can write:

or

or

The \ indicates that it should be considered a character in the string rather than a string delimiter.

Conclusion

There are several ways to combine strings together in JavaScript.

Template literals and join method is convenient for joining strings together.

Written by

Web developer. Subscribe to my email list now at http://jauyeung.net/subscribe/. Email me at hohanga@gmail.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store