Tip 4: Variables to Readable Strings with Template Literals
In this tip, you will learn how to convert variables into new strings without concatenation.
We'll cover the following
Combining strings
Strings are messy. That’s all there is to it. When you’re pulling information from strings, you have to deal with the ugliness of natural language: capitalization, punctuation, misspellings. It’s a headache.
Collecting information into strings is less painful, but it can still get ugly quickly. Combining strings in JavaScript can be particularly rough, especially when you combine strings assigned to variables with strings surrounded by quotes.
Example
Here’s a situation that comes up all the time: You need to build a URL. In this case, you’re building a link to an image on a cloud service. Your cloud service is pretty great, though. In addition to hosting the asset, you can pass query parameters that will convert the asset in a variety of ways (height, width, and so on).
To keep things relatively simple, you’re going to make a function that creates a URL by combining your cloud provider URL with the ID of the image and the width as a query parameter.
To keep things complicated, you’re going to combine regular strings with
strings that are returned from a function, strings that are assigned to variables,
and strings that are converted right before concatenation. You’re going
to use a function (implemented elsewhere) that will return a cloud provider
such as pragprog.com/cloud. Your function will take ID and width
as parameters,
but it will need to parse the width
to make sure it’s an integer.
URLs get particularly ugly because you have to add slashes between the parts
of a route along with the building blocks of queries such as ?
, =
, and &
. Traditionally,
you have to combine each piece with a +
sign.
The final result looks like this:
Get hands-on with 1400+ tech skills courses.