How to Write JavaScript Strings

Hey - Nick here! This page is a free excerpt from my $99 course JavaScript Fundamentals.

If you want the full course, click here to sign up and create an account.

I have a 30-day satisfaction guarantee, so there's no risk (and a ton of upside!) in signing up for this course and leveling up your JavaScript developer skills today!

There are 7 types of data structures in JavaScript:

  • String
  • Number
  • Object
  • Boolean
  • Null
  • Undefined
  • Symbol

In this lesson, you’ll start your education on JavaScript types by learnings how to write JavaScript strings.

What Are JavaScript Strings?

A string is anytime that you have characters that are held together. Strings are called strings because they are strings of characters. Said differently, strings are used for holding text in JavaScript.

Strings can be created using three different characters in JavaScript:

  • Single-quotes: '
  • Double-quotes: "
  • Backticks: `

Here are three examples of string creation using each of the characters listed above:


const first = 'Nick';

const last = "McCullum";

const city = `Fredericton`;

Single-quotes and double-quotes perform exactly the same functionality in JavaScript. The reason we have to be able to use both ' and " characters in JavaScript is in case we’re writing a string that includes either character.

As an example, the following string needs to be created with " characters since it contains a ' character:


const sentence = "It's a great day to be alive!";

If you instead wrote this string using single-quotes, like this:


const sentence = 'It's a great day to be alive!';

Then JavaScript would return the following error:


Uncaught SyntaxError: Unexpected identifier

How To Write Strings With Backticks in JavaScripts

Backticks have slightly different functionality than either single-quotes or double-quotes. They are also much newer.

JavaScript’s ES2015 specification - introduced in the year 2015 - allowed developers to create strings (called template strings or template literals) using backticks for the first time. This new JavaScript functionality made serious improvements over the traditional methods of working with strings.

Let’s work through each of the benefits of creating JavaScript strings with backticks.

First of all, since you will rarely include the ` character in your strings, you do not have to worry about that character inadvertently breaking a string. Said differently, you’ll rarely experience the Uncaught SyntaxError: Unexpected identifier error that we just encountered.

The second benefit of creating strings using backticks is that you can easily create multi-line strings.

As an example, this is a perfectly valid string in JavaScript:


const sentence = `It's

A

Great

Day

To

Be

Alive!`;

If you tried to write the same string using single-quotes or double-quotes, you would need to include the \ escape character at the end of each line. This makes your code much less readable.

The last advantage of using backticks to write JavaScript strings is that they allow for variable interpolation. Variable interpolation means passing a variable’s name into a string, and having the string include the value of that variable (instead of its variable name).

To perform variable interpolation, we pass a variable’s name into the $ and {} characters. Here is an example:


city = 'Fredericton';

name = 'Nick';

sentence = `My name is ${name} and I live in ${city}.`;

The code contained within the curly brackets has access to all of your normal JavaScript functionality.

As an example, here is one case where you might want to include addition inside of these curly brackets:


age = 24;

sentence = `I am ${age} years old. After my next birthday, I will be ${age+1}`;

This returns:


"I am 24 years old. After my next birthday, I will be 25."

To give some context about why this type of variable interpolation is so useful, let’s consider how we would have performed variable interpolation prior to JavaScript’s ES2015 specification.


city = 'Fredericton';

name = 'Nick';

sentence = 'My name is ' + name + ' and I live in ' + city + '.';

While this code technically performs the same function as the original example that we encountered, it is much less readable. Using the ES2015 specification’s backticks allows us to reserve the + character for the addition of numbers, not the concatenation of strings.

For the rest of this article, we will work through some of the most important functionality that you should know with respect to JavaScript strings.

How to Calculate the Length of a JavaScript String

Every JavaScript string contains an attribute called length which tells you how many characters are contained within the string.

You can access the length attribute using the dot operator. Here is an example:


food = 'Fish';

food.length;

This returns 4.

How to Access a Character From a JavaScript String

You can access a specific character from a JavaScript string by passing the index of that character into square brackets on the end of the variable name.

Here is an example:


capitalCity = 'Ottawa';

capitalCity[4];

This code returns w

Note that since JavaScript is a zero-indexed programming language, then the first character has index 0, the second character has index 1, and so on.

How to Change a Character in a JavaScript String

Just like we were able to access a specific character from a JavaScript string in the last section of this tutorial, we can also modify characters in a string.

However, the syntax is different. Unlike in certain other programmers languages (like Python), you can’t simply reference the character and assign a new value to it using the = assignment operator.

To see what I mean, consider the following JavaScript code:


capitalCity = 'Ottawa';

capitalCity[4] = 'Z';

capitalCity;

After the capitalCity[4] = 'Z' statement, the capitalCity variable will still return Ottawa.

Why is this?

It’s because JavaScript strings are immutable, which means that they cannot be modified after creation. Because of this, the only way to modify a string is to overwrite it.

Said differently, here’s the statement we would need to run to replace the w with Z in Ottawa:


capitalCities = 'OttaZa'

How to Split a JavaScript String

There are many cases where you will want to take a JavaScript string and split it into several smaller substrings.

The main way that you’ll do this is by splitting a string each time a specific character occurs. A common example of this is splitting on the space character, which will generate a list of all the words in the string.

We use JavaScript’s split method to do this. To split a string, you call the split method on it using the dot operator, like this:


sentence = 'This is a sentence.';

sentence.split(" ");

The output of this code is:


["This", "is", "a", "sentence."]

We have not seen the [ and ] characters in JavaScript yet, but we will learn later in this course that they are used to create JavaScript arrays.

How to Transform a JavaScript String to Uppercase Letters

Another common use case in working with JavaScript strings is to transform all of the characters to uppercase letters. The toUpperCase method solves this problem.

To apply this method to a JavaScript string, you can call it by appending it to the end of a variable name along with the dot operator, like this:


exampleString = 'these letters will all be turned to uppercase.';

exampleString.toUpperCase();

Here’s the output of this code:


"THESE LETTERS WILL ALL BE TURNED TO UPPERCASE."

How to Transform a JavaScript String to Lowercase Letters

Just as we could transform a string to all uppercase letters using the toUpperCase method, we can also transform a string to all lowercase letters using the toLowerCase method.

Here is an example:


uppercaseString = 'THESE SHOULD BE LOWERCASE AFTER THE METHOD IS APPLIED';

uppercaseString.toLowerCase();

Here is the output of this code:


"these should be lowercase after the method is applied"

Final Thoughts

In this lesson, you learned how to write JavaScript strings. Over the next several lessons, we will learn about other data structures in JavaScript, including numbers and objects.

As a quick reminder, this page is a free excerpt from my $99 course JavaScript Fundamentals. Click here to sign up now!