This article teaches how to check if a string contains a substring in JavaScript. It’s helpful for you.To check if a substring exists in a string, you can use either .includes() or .indexOf().
Check if a string contains a substring
Using String.includes(str value, int position)
The most straightforward way, the function simply returns true/false
on whether the value parameter exists in that string, that also includes substrings.
Additionally you can check from the starting position of the position parameter until the end of the string.
Syntax:
String.includes(str value);
Parameters:
Name | Type | Description |
---|---|---|
value | string | The value to find in the string. |
position | int? | The starting position to find the value, defaults to 0 if not set. |
Code:
const str = "def-abc-123";
console.log(str.includes("123"));
console.log(str.includes("def"));
console.log(str.includes("def",4));
Output:
true
true
false
Note here how the third .includes()
return false despite the string clearly containing "def"
, it is because the function is searching for the substring starting at position 4
, which means that the function is searching through "abc-123"
and not "def-abc-123"
.
Using String.indexOf(str value, int position)
Is almost the same thing as .includes()
but instead of returning true/false
, it returns the index of the first occurrence of the value starting from the position parameter and returns -1
if nothing is found.
Besides being used to check if value exists in the string, it also returns the index, which can have some other utilities.
Syntax:
String.indexOf(str value, int position);
Parameters:
Name | Type | Description |
---|---|---|
value | string | The value to find in the string. |
position | int? | The starting position to find the value, defaults to 0 if not set. |
Code:
const string = "def-abc-123";
function findSub(sub, str, position=0) {
if (str.indexOf(sub, position) != -1)
console.log(`"${sub}" found at:${str.indexOf(sub, position)}`);
else
console.log(`"${sub}" not Found!`);
}
findSub("123", string);
findSub("def", string);
findSub("def", string, 4);
Output:
"123" found at:8
"def" found at:0
"def" not Found!
Summary
To check if a string contains a substring in JavaScript, you use either .includes()
for simplicity or .indexOf()
which has more utility as it gives you the index not just true/false
. While only somewhat related, the .charAt()
function can also give you the character at the index and the .substring()
and the .slice()
function to get substrings.
Maybe you are interested:
- Replace all hyphens in a string in Javascript
- Remove all non-alphanumeric characters from string in JS
- Get the first Character of a String in JavaScript

Hello, my name is Davis Cole. I love learning and sharing knowledge about programming languages. Some of my strengths are Java, HTML, CSS, JavaScript, C#,… I believe my articles about them will help you a lot.
Programming Languages: Java, HTML, CSS, JavaScript, C#, ASP.NET, SQL, PHP