Build awareness and adoption for your software startup with Circuit.

How to Check if a String Contains a Substring in JavaScript

Unveiling JavaScript's Secrets to Substring Detection!

If you are a web developer, you might have encountered situations where you need to check if a string contains a substring in JavaScript. For example, you might want to validate user input, extract some information from a text, or perform a search operation. How can you do that in JavaScript?

In this blog post, I will show you:

  • Learn about substrings and why they matter
  • Explore different ways to find substrings in JavaScript code
  • Try the indexOf(), includes(), search() and regex methods

Four different ways to check if a string contains a substring in JavaScript, and compare their advantages and disadvantages.

By the end of this post, you will be able to choose the best method for your needs and write efficient and readable code.


Before diving deep, if you want to build secure JavaScript and Node JS applications download the "JavaScript Security Cookbook (Over 40+ recipes)" for FREE!

JavaScript Security Cookbook


What is a Substring?

Let's talk about substrings.Ā What are they?Ā They are parts of a string that fit inside another string.Ā For example, "Hello" fits inside "Hello world".Ā It is a substring.

A substring can be anywhere in a string:Ā at the start, in the middle, or at the end.Ā It can also be the same as the whole string.Ā Or it can be nothing at all, with no characters.

Why Check for Substrings?

Sometimes you need to find a smaller string inside a bigger one in JavaScript. This can help you with many things, such as:

  • Making sure users enter valid data, like emails, passwords, or phone numbers
  • Looking for specific words or phrases in a text or a web page
  • Sorting or filtering data based on some rules or patterns
  • Changing or fixing text, such as replacing, splitting, or joining strings

How to Check for Substrings in JavaScript

There are several ways to check if a string contains a substring in JavaScript, depending on your needs and preferences. Some of the most common methods are:

  • Using theĀ indexOf()Ā method
  • Using theĀ includes()Ā method
  • Using theĀ search()Ā method
  • Using regular expressions

Method 1: Using theĀ indexOf()Ā to check if a string contains a substring

Do you want to learn how to find a part of a text in JavaScript? Then you should know about the indexOf() method! This method is very useful and easy to use. It can tell you where a substring appears in a string, or if it doesn't appear at all.

JavaScript string indexOf() method

Let's see an example:

// Check whether the substring exists in a string using the indexOf() method
let message = "JavaScript runs everywhere on everything!";
let substring = "everywhere";
console.log(message.indexOf(substring));
// Output: 16

TheĀ indexOf()Ā method is case-sensitive, meaning that it will only match the exact characters of the substring. For example:

// Check where substring exists in a string (case-sensitive search is the default)
let message = "JavaScript runs everywhere on everything!";
let substring = "Everywhere";
console.log(message.indexOf(substring));
// Output: -1

Sometimes you want to find out if a string has another string inside it. But what if they have different capital letters? No problem! You can use two handy methods called toLowerCase() and toUpperCase(). They change all the letters in a string to lower case or upper case. Then you can use another method called indexOf() to see if one string is in another. Like this:

// Check whether the substring exists in a string in a case-insensitive manner
let message = "JavaScript runs everywhere on everything!";
let substring = "Everywhere".toLowerCase();
console.log(message.toLowerCase().indexOf(substring));
// Output: 16

Do you want to learn a cool trick with the JavaScript indexOf() method? You can tell it where to start looking for a substring in a string! This is handy when you only care about the part of the string after a certain point.

Let me show you an example:

// Incremental search using indexOf() method
let message = "JavaScript runs everywhere on everything!";
let substring = "Every".toLowerCase();
console.log(message.toLowerCase().indexOf(substring, 17));
// Output: 30

How do you find out if a string does not have a certain part? It's easy! You just need to use the !== operator. This operator compares two things and tells you if they are different. You can use it with the indexOf() method. This method looks for a part of a string inside another string. It gives you a number that shows where the part is. If the part is not there, it gives you -1. So, you can compare the result of indexOf() with -1 using !==. If they are different, it means the part is there. If they are the same, it means the part is not there. Here is an example:

// Ensure the given substring is not in a string
let message = "JavaScript runs everywhere on everything!";
let substring = "World";
console.log(message.toLowerCase().indexOf(substring.toLowerCase()));
// Output: -1

Method 2: Using theĀ includes()Ā method to check if a string contains a substring

Do you want to know if a string has another string inside it? There is a simple and new way to do that in JavaScript. It is called the JavaScript includes() method. This method gives you a true or false answer. It tells you if a string contains a substring or not.

JavaScript string includes() method

Let me show you an example:

// Check for substring using includes() method (case-sensitive is default)
let message = "JavaScript runs everywhere on everything!";
let substring = "every";
console.log(message.includes(substring));
// Output: true

The includes() method is very picky about the letters you use. It only matches the same ones, so you have to be careful with the upper and lower cases. But don't worry, there's a trick you can use to make it more flexible. Just like the indexOf() method, you can change the strings to all lower case or all upper case before you use the includes() method. That way, you can find any word you want, no matter how it's written.

// Check for substring using includes() method in case-insensitive manner
let message = "JavaScript runs everywhere on everything!";
let substring = "Every".toLowerCase();
console.log(message.toLowerCase().includes(substring));
// Output: true

TheĀ includes()Ā method also accepts a second argument, which is the starting index from which to search for the substring. For example:

// Incremental search using includes() method
let message = "JavaScript runs everywhere on everything!";
let substring = "Every".toLowerCase();
console.log(message.toLowerCase().includes(substring, 17));
// Output: true

To check if a string does not contain a substring, you can use theĀ !Ā operator to negate the result of theĀ includes()Ā method. For example:

// Case insensitive search using includes() method
let message = "JavaScript runs everywhere on everything!";
let substring = "World".toLowerCase();
console.log(!message.toLowerCase().includes(substring));
// Output: true

Method 3: Using theĀ search()Ā method to check if a string contains a substring

The JavaScript search() method gives you the position of the first match, or -1 if there is no match. But wait, there's more! You can also use a regular expression to tell the search() method what kind of text you are looking for. A regular expression is like a secret code that describes the pattern and rules of the text. For example:

// Using search() method to check substring
let message = "JavaScript runs everywhere on everything!";
let substring = "every";
console.log(message.search(substring));
// Output: 16

Regular expressions are a powerful tool for working with strings, but they can also be quite complicated and tricky to master. If you are not familiar with them, you can check out this tutorial to learn more about them.

One of the advantages of using regular expressions is that you can easily ignore the case of the substring by using theĀ iĀ flag. For example:

// Regular expression with case-insensitive flag
let message = "JavaScript runs everywhere on everything!";
let substring = /EVERY/i;
console.log(message.search(substring));
// Output: 16

You can also use other flags and modifiers to customize your regular expression, such as:

| Expression | Description | | :------------- | ---------------------------- | | g | Global searchĀ  | | m | Multiline search | | ^Ā  | Start of the stringĀ  | | $Ā  | End of the stringĀ  | | [] | Character setsĀ  | | . | Any characterĀ  | | * | Zero or more repetitionsĀ  | | + | One or more repetitionsĀ  | | ? | Zero or one repetitionĀ  | | () | Grouping | | \| | Alternation | | \ | Escaping special characters. |

Method 4: Using regular expressions to check if a string contains a substring

Regular expressions are amazing! They let you check if a string has a substring in JavaScript. But that's not all they can do. You can also use other methods with regular expressions, like:

4.1 Using match() method

TheĀ match()Ā method, which returns an array of all the matches of a regular expression in a string, or null if no matches are found. For example:

// Regular expression with case-insensitive and global flags, and optional group
let message =
  "JavaScript runs everywhere on everything! Using JavaScript you can build all types of apps.";
let substring = /JavaScript( runs)?/gi;
console.log(message.match(substring));
// Output: ["JavaScript runs", "JavaScript"]

4.2 Using test() method

TheĀ test()Ā method, which returns a boolean value indicating whether a regular expression matches a string or not.

For example:

// Regular expression literal
let message = "JavaScript runs everywhere on everything!";
let substring = /every/;
console.log(substring.test(message));
// Output: true

4.3 Using replace() method

The replace() method is a great way to transform a string. It lets you find some parts of the string that match a pattern and change them with something else. You can use another string or a function to do the replacement.

Here is an example:

// Regular expression literal
let message = "JavaScript runs everywhere on everything!";
let substring = /everything!/;
let replaceString = "any device!";
let newMessage = message.replace(substring, replaceString);
console.log(newMessage);
// Output: "JavaScript runs everywhere on any device!"

4.3 Using split() method

Do you want to learn how to split a string into smaller pieces? You can use the JavaScript split() method for that! It's a handy tool that takes a string and a regular expression or another string as arguments. It then breaks the string into an array of strings, using the regular expression or the other string as separators.

For example:

// Regular expression literal
let message = "JavaScript runs everywhere on everything!";
let substring = /every/;
console.log(message.split(substring));
// Output: [""JavaScript runs ", "where on ", "thing!"]

The code uses a regular expression (/every/) to split the 'message' string into an array of substrings at occurrences of the specified pattern ('every'). The resulting array is then logged to the console.

Conclusion

In this blog post, you have learned how to check if a string contains a substring in JavaScript, using various methods and techniques. There are several ways to check if a string contains a substring in JavaScript, depending on your needs and preferences, such as:

  • To find the first index of a substring, use indexOf(). It returns -1 if not found.
  • To check if a substring exists, use includes(). It returns true or false.
  • To search for a substring with a regular expression, use search(). It returns the first match index or -1.
  • To use complex patterns and rules for substrings, use regular expressions. They work with methods like match(), test(), replace(), and split().
  • You learned how to ignore cases, specify the start index, and check for the absence of substring with different techniques and operators.

I hope that this blog post has been helpful and informative for you and that you have gained a better understanding of how to check if a string contains a substring in JavaScript.





Continue Learning