In this tutorial, we will dive into JavaScript strings and explore ways we can work with and manipulate them.
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.
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:
JavaScript will get confused and produce an error. You can either use the single quote option, like:
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:
Check out these in the editor below. Try creating your own string, with two different techniques, that says ‘No, I’m not a banana.’
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:
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:
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.
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:
Check out a few more examples in the editor below. Try to guess what will be printed before you run it!
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.
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?
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!
If you want to extract part of a string, using the substring method makes it quick and easy!
See the editor below for a few examples.
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.
This is best understood with a few examples, so see below!
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:
And the second is using a for...of
loop:
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!