Introduction
If you want to work in JavaScript, you need to be familiar with strings. A string is a sequence of characters that can be letters, numbers, or symbols. In terms of quantity, it can be one or more than one character. Each character in a string is associated with a number. This is the index number that you can use to access that specific character.
You can apply a variety of methods and properties to all kinds of strings. There is a lot more that you need to learn in order to effectively utilize strings when working in JavaScript. One of the most important things you should know is how to make the distinction between string primitives and string objects.
In this guide, we will show you how to differentiate string primitives and string objects in JavaScript. We will also discuss how you can index strings, access individual characters, and use some common properties and methods.
Types of Strings
Let’s begin by determining what the two types of strings are. First, we have the string primitive which is an immutable data type. Secondly, we have the String
object. A better way to understand the difference between the two is with a practical example. Let’s initialize a string primitive and a string object to test the difference:
1 2 3 4 5 |
// Initializing a new string primitive const stringPrimitive = "A new string."; // Initializing a new String object const stringObject = new String("A new string."); |
Now we need to determine the type of value. For this purpose, we will use the typeof
operator. We will be assigning a string to a variable, like so:
1 |
typeof stringPrimitive; |
1 2 |
Output string |
For our next example, we will create a strong object and assign it to a variable. We will use the String()
function here:
1 |
typeof stringObject; |
1 2 |
Output object |
It is important to know the difference because JavaScript is constantly performing conversions from primitive to object and vice versa every time you call a method. However, you will create string primitives most of the time. This is because JavaScript can access and apply properties to the String
object wrapper without modifying the primitive.
How to Index Strings
Now that we know a little about what strings are, let’s explore how we can index them. Each character on a string corresponds to an index number. The index numbers start from 0 and go up to however many characters you are using. Consider this example:
Here, we have made a string with the value How are you?
. As you can see, the first character H
corresponds to the first index which is 0
. The last character ?
corresponds to the last number 11
. An important thing to notice here is that whitespaces also count as characters. This means that you have to index them as well. In the above example, the index numbers for the whitespaces are 3
and 7
.
The benefit of such indexing is that it allows you to manipulate the strings in a lot of ways. This is because you can access each character individually.
How to Access Characters
Next, we will see how we can access the characters. We shall continue the previous How are you?
example:
1 |
"How are you?"; |
You can access characters from this string using square bracket notation. Say you want to access character number 5:
1 |
"How are you?"[5]; |
1 2 3 |
Output r |
Another way to access characters is by using the charAt()
method. This also allows you to access the character after specifying the index number:
1 |
"How are you?".charAt(5); |
1 2 3 |
Output r |
Similarly, to return the index number by first instance of the character, use indexOf()
:
1 |
"How are you?".indexOf("o"); |
1 2 3 |
Output 1 |
This means that you will get the instance when the letter ‘o’ appears for the first time in the string. Naturally, to get the last instance of the character, use lastOf()
:
1 |
"How are you?".lastIndexOf("o"); |
1 2 3 |
Output 9 |
You can use the above two commands with multiple characters as well. You will get the index number of the first character in the instance:
1 |
"How are you?".indexOf("are"); |
1 2 3 |
Output 4 |
The slice()
method can also be used. It gives you the characters between two index numbers. The first parameter is the starting number. The second is the ending index number. Here is an example:
1 |
"How are you?".slice(8, 11); |
1 2 3 |
Output you |
The function will not return the character at the specified index number. Similarly to the above example, it does not return ?
as part of the output even though it is at index number 11
. If you want to get all characters from a starting parameter to the end of the string, simply do not enter the ending parameter:
1 |
"How are you?".slice(8); |
1 2 3 |
Output you? |
How to Find the Length of a String?
It is very easy to find the length of a string. You just have to use the length
property:
1 |
"How are you?".length; |
1 2 3 |
Output 12 |
The length gives you the number of characters in the string. A string with characters starting from 0
and ending at 11
has 12 characters.
Can You Shift Between Upper and Lower Case Characters?
It is possible to make conversions between upper and lowercase letters in your JavaScript strings. To do this, you can use the built-in functions of toUpperCase()
and toLowerCase()
.
1 2 |
Example: "How are you?".toUpperCase(); |
1 2 |
Output HOW ARE YOU? |
Similarly, converting into lowercase:
1 |
"How are you?".toLowerCase(); |
1 2 |
Output how are you? |
Note that applying these methods does not change the original string.
How to Split Strings?
You can split any string by a character using the split()
method. Then, you can make a new array from the sections. There will be whitespace separating the array shown with " "
. Splitting allows you to determine how many words a sentence has:
1 2 3 4 |
const originalString = "How are you?"; // Split string by whitespace character const splitString = originalString.split(" "); console.log(splitString); |
1 2 |
Output [ 'How', 'are', 'you?' ] |
Now the splitString
variable has a new array. To access each section, you need to refer to the index number:
1 |
splitString[1]; |
1 2 3 |
Output are |
Giving an empty parameter to the method will make an array separated with commas.
How to Remove Whitespace from the Ends of the Strings
The trim()
method allows you to remove whitespace from the front or the end of the string. However, you cannot use it to remove whitespaces from between the characters. Whitespaces represent tabs as well as spaces:
1 2 3 |
const tooMuchWhitespace = " How are you? "; const trimmed = tooMuchWhitespace.trim(); console.log(trimmed); |
1 2 |
Output How are you? |
How to Replace String Values
It is possible for you to search and replace values in your string. Use the replace()
method for this:
1 2 3 4 |
const originalString = "How are you?" // Replace the first instance of "How" with "Where" const newString = originalString.replace("How", "Where"); console.log(newString); |
1 2 |
Output Where are you? |
As you can see, the first parameter is the value you want to find. The second character is the one you want to replace it with.
Another feature in JavaScript is that you can use Regular Expressions with replace()
. Let’s say you want to catch all instances of a value instead of just the first one. You can use the g
global flag to do so. The i
case insensitive flag will ignore the case:
1 2 3 4 |
const originalString = "Javascript is a programming language. I'm learning javascript." // Search string for "javascript" and replace with "JavaScript" const newString = originalString.replace(/javascript/gi, "JavaScript"); console.log(newString); |
1 2 |
Output JavaScript is a programming language. I'm learning JavaScript. |
Conclusion
Strings are used a lot in JavaScript and understandably so. It is a data type that offers a lot of functionality and possibilities. Now you know the difference between a string primitive and an object. You also have the basics down for string indexing, text formatting, and accessing characters or index numbers. Lastly, we also saw how to find and replace values in the string.
Here are more resources from our blog that will help you further utilize JavaScript:
- Learn how prototypes and inheritances operate on JavaScript.
- In this tutorial, we explore in detail how you can add JavaScript to HTML.
- If you are building your own web application, take a look at our guide on how to choose the best server setup.
Happy Computing!
- Removing Spaces in Python - March 24, 2023
- Is Kubernetes Right for Me? Choosing the Best Deployment Platform for your Business - March 10, 2023
- Cloud Provider of tomorrow - March 6, 2023
- SOLID: The First 5 Principles of Object-Oriented Design? - March 3, 2023
- Setting Up CSS and HTML for Your Website: A Tutorial - October 28, 2022