Please enable JavaScript to use CodeHS

Working With Strings in JavaScript

In this tutorial, we will dive into JavaScript strings and explore ways we can work with and manipulate them.

By Ryan Hart

In the world of computer science, a string is a finite list of characters, like letters and numbers. For example, “hello world” and “ALPHA12345” are both strings. JavaScript provides a plethora of operators, methods, and functions that allow the programmer to manipulate strings efficiently and fairly easily, which we’ll explore in this tutorial.

An embedded gif that reads: str= "I'm a string!"

String Basics

To create a string, you can bookend your characters with either single quotes or double-quotes. Often strings are stored in variables to be used elsewhere in the program.

The example below illustrates the creation and printing of strings.

Sometimes you’ll want to include quotes within the content of the string, but if you type:

let quote = "Becca said, "Yes," so we should send her the invite";
JavaScript

JavaScript will get confused and produce an error. You can either use the single quote option, like:

let quote = 'Becca said, "Yes," so we should send her the invite';
JavaScript

Or place a backslash (\) in front of the quote to escape the character. The backslash turns special characters, like single or double quotes, into strings themselves. Adding backslashes to the first attempt, you’d get:

let quote = "Becca said, \"Yes,\" so we should send her the invite";
JavaScript

Check out these in the editor below. Try creating your own string, with two different techniques, that says ‘No, I’m not a banana.’

Concatenating Strings

To join two or more strings, or string variables, together, you can concatenate them using a plus sign (+). Although the plus sign is also used to add numbers, JavaScript is able to tell the difference between string + string (or number), which concatenates as a string, versus number + number, which results in a numerical calculation.

Take a look at a few different examples here:

The Length Property

Every string created in JavaScript has a length property that returns the number of characters of the string. You can use the dot notation to access it, like string.length. Notice that it is not a method, so you do not include any parentheses. Here is a simple example:

let password = "Alw@ysHUngRY";
console.log(password.length);        // prints 12
JavaScript

You may have a situation where you just want to know the length of the string, like in requiring a password to be at least 8 characters long, but often it is used when you want to access the individual characters, as you’ll see later.

String Indices

Each character in a string has a specific location or address, called an index. This allows the programmer to access specific characters of the string.

In the image above, “Hey there.” is the string, and in red, you see the index for each character in the string. A couple of important things to notice:

  • The indices of a string ALWAYS starts with 0 and then increases by 1 with each character.

  • Every character gets an index, including the space and the period.

  • String variables are immutable, which means we cannot use the index to change a character directly (we’d have to re-assign it to a variable).

To access the characters in the string, use square brackets at the end of the string with the index of the desired character inside. For example:

let name = "Fran";
console.log(name[0]);    // prints F
console.log(name[3]);    // prints n

// Careful though, we cannot do the following, since strings are immutable:
name[0] = "B";
JavaScript

Check out a few more examples in the editor below. Try to guess what will be printed before you run it!

String Methods

This is where is starts to get fun! There are many actions, or methods, that can be used with strings. These allow us to access, work with, and manipulate them with ease! Below you will see the following groupings of methods with examples: Searching, Extracting, and Manipulating.

1. Searching Strings

There are many cases in which you might need to learn more about the contents of a string or find where a specific substring exists within the string. Below are a handful of methods that help with this process:

  • string.includes(substring, [optional index]) - checks to see if a string contains a substring. Returns true if found, otherwise false.

  • string.search(regexp) - finds the first occurrence of the regular expression within a string. Returns the index of the substring if found, otherwise returns -1.

  • string.indexOf(substring, [optional starting index]) - similar to .search(), but finds the first occurrence of a substring within a string. Returns the index of substring if found, otherwise returns -1.

  • string.lastIndexOf(substring, [optional starting index]) - same as .indexOf(), but starts at the end and finds the last occurrence of a substring within a string. Returns the index of the substring if found, otherwise returns -1.

  • string.startsWith(substring, [optional index]) - determines if the string starts with the substring. Returns true if it does, otherwise returns false.

  • string.endsWith(substring, [optional index]) - determines if the string ends with the substring. Returns true if it does, otherwise returns false.

Check out the program below to see these in action. Can you guess the correct outputs before you run it?

2. Manipulating Strings

Our final grouping includes methods that all relate to manipulating a string. In order to capture the new result, be sure to re-assign the value back to the same variable or a new variable.

  • string.replace(substring, newSubstring) - returns a new string with newSubstring replacing the first occurrence of the substring.

  • string.replaceAll(substring, newSubstring) - returns a new string with all of the occurrences of substring being replaced with newSubstring.

  • string.trim() - returns a new string with all of the whitespace removed from both ends of the string. It does not remove the space characters that are in between other characters.

  • string.toUpperCase() - returns a new string where every letter character is in uppercase.

  • string.toLowerCase() - returns a new string where every letter character is in lowercase.

Check out the examples below to see these in action!

3. Extracting Strings

If you want to extract part of a string, using the substring method makes it quick and easy!

  • string.substring(starting index, [optional ending index]) - returns the substring between the starting index (inclusive) and the end, or optionally the ending index (non-inclusive).

See the editor below for a few examples.

3.5 Extracting Strings, Pt 2

A final method worth mentioning is the split() method. This gets its own section because it’s a powerful method that splits a string into an array, providing easy access to a series of substrings from the original string.

  • string.split(separator, [optional limit]) - returns an array with substrings that were separated by the determined separator in the original string.

This is best understood with a few examples, so see below!

String and Array Iteration

In this final section of the tutorial, we want to cover the technique of iterating through all of the characters in a string and items in an array. When working with strings and arrays, this can be a powerful way to check and/or manipulate the contents of these two variables.

There are two easy ways to iterate through both strings and arrays. The first is taking advantage of the length property:

let example = "Happy Friday!";
for (let i = 0; i < example.length; i++) {
    console.log(example[i];
}
JavaScript

And the second is using a for...of loop:

let example = "Happy Friday!";
for (let letter of example) {
    console.log(letter);
}
JavaScript

Both will produce the same results, and both techniques work for arrays as well. Which you use depends on whether or not you need the index of the items, or if you just want the values.

See these examples in the editor below!