Find a Substring in a String with JavaScript

With the use of JavaScript, we have so many string methods available to us to perform almost any action imaginable to a word or string. We can manipulate, add and remove characters, and even find the location of a string inside another string. If you need to perform an intricate or even a minuscule task, the capability is there. Today, we’ll be seeing if a substring exists in a string using plain, delicious vanilla JavaScript.

There’s always a point in a project where we need to see if a certain set of characters exists inside another with JS. Because of situations like that, I always have functions from previous projects that I’ve created at the ready, and this article provides you with a few. Using these choice JavaScript string methods, we’ll come up with multiple ways to check if a string exists inside another string.

Using the indexOf() method

With the indexOf method, finding our string will be comparable to finding a needle in a haystack, but a tiny bit easier. Let’s go through this step by step to show you exactly how it’s done. First, we will make a string variable named s that will be the word we are searching through. This will be the “haystack.”

var s = "my name is ron";

Next, we’ll use the indexOf method to search through the string noted above. We should make another variable to save the output of the indexOf function.

var x = s.indexOf("name");
  • If “name” is found inside “my name is ron”, x will be a positive value.
  • If “name” is not found inside of the string variable, the variable x will be -1.

 

Let’s make a conditional that tests if the x variable is bigger than -1, which means it exists in s.

if (x > -1){ console.log('substring exists!'); }

We can insert another parameter in the indexOf method call. This second parameter of the indexOf syntax determines where we want to start searching in our haystack variable, s. For this example, we’ll start at the character with the index of 5 and see if the term “name” is still in the s variable.

var x = s.indexOf("name", 5);

The variable x is now equal to -1. This means “name” doesn’t exist in the string “my name is ron” when we start at the character with the fifth index.

Using the search() method

We can also use JavaScript’s search method to find a substring inside of a string. The cool thing about using the search method is that we can use regular expressions as well as plain text. With search, we can also determine whether or not we want to determine the case sensitivity of the string we’re looking for.

The syntax for search and indexOf are the same. Here’s an example of how to use the case-insensitive feature with search.

var s = "Welcome to My Site!";
var x = s.search(/site/i);

 

Leave a Comment