A substring is a smaller piece of text inside a larger one. One of the most common tasks when working with strings in JavaScript is checking whether a substring exists. And if it does, you might want to extract it or use it somehow.
Let’s break this down into two parts: checking and extracting.
Checking if a String Contains a Substring
JavaScript gives you several ways to do this, but the simplest and most readable is .includes().
If the substring is found anywhere in the string, .includes() returns true. If not, it returns false.

Note: This method is case-sensitive, so “javascript” would return false in the above example.You can also use includes() to search for a substring within a string by providing a second parameter to specify the starting index:

Starting the search from a different index can return false:

Note: The includes() method does not provide information on where the substring is situated in the string or how often does it appear.If you need information on where the substring resides in the string, other methods, such as the indexOf() method might be more suitable.

Extracting a Substring from a String
Once you know a substring exists, you can extract it using .slice().

Here’s how you’d extract “JavaScript” from the sentence above:

Use Case: Find and Print a Keyword in a Sentence
For this example, we scan a sentence; if we find the substring ‘pioneer’, we extract it for use.

The substring is print as expected:

What’s Happening Here?
- You start with a string:
bio = “Ada Lovelace was a pioneer in computing.”; - You want to check if the word “pioneer” is in the sentence.
Step 1: Check if it’s there

- Returns
trueif the word is found. - This is a quick way to avoid unnecessary logic if the word isn’t present at all.
Step 2: Get its starting position

- This tells you the index (character position) where the word starts.
- In this case, it returns
22because“pioneer”begins at the 22nd character in the string.
Step 3: Slice out the exact word

- You use
.slice()to extract just the word, using:start=22end=22 + 7→29, because“pioneer”is 7 characters long.
- The result is
“pioneer”, which you can now use however you want.
In Summary
- Use
.includes()when you just want to check if a substring exists. - Use
.indexOf()to find where it starts. - Use
.slice()or.substring()to extract it once you know the position.
These are simple yet powerful tools to check and manipulate text instantly—perfect for searches, filters, and formatting.