Check if a string contains a substring in Javascript


Check if a string contains a substring in Javascript

In this article, we will learn how to check if a string contains a substring using JavaScript.

JavaScript provides us with many in-built methods which helps us to check for a substring in a string.

Here, we will be learning about three different JavaScript methods, includes(), indexOf() and search() method which will help us to perform the operation.

So, lets check for the substring using these in-built methods.

Using includes() to find sub-string

This is one of the easy and simple way to perform the operation. We will use the includes() method to check if a string have a specific substring or not.

includes() returns true if the substring is present otherwise it will return false.

Example:

const text = "I have a blue cat in a red box"
console.log(text.includes('blue')) //true
console.log(text.includes('black')) //false

Note: includes() method is case-sensitive. so, abc and ABC are not same.

Using indexOf() to find sub-string

We can also check if a string contains a particular substring using pre-ES6's indexOf() method in JavaScript.

It search for the text / substring and when it finds the match, it returns the first occurrence (index) of it as a result. If the substring is not found it returns us -1.

Example:

const text = "I have a blue cat in a red box"
console.log(text.indexOf('blue')) // 9
console.log(text.indexOf('black')) // -1

// FOR TRUE AND FALSE AS RESULT

console.log(text.indexOf('blue') !== -1) // true
console.log(text.indexOf('black') !== -1) // false

Note: indexOf() method is case-sensitive.

Using search() to find sub-string

The search() method in JavaScript is use to search a text / string for a value.

It returns the index (position) of the string if a match is found. If no matching string is found it returns -1.

The search value can be a string or a regular expression.

Example:

const text = "I have a blue cat in a red box"
console.log(text.search('blue') !== -1) // true
console.log(text.search('black') !== -1) // false

Note : The search() method is case-sensitive too.

Related Topics :

Check If String Is A Number Or Not In JavaScript

Check if a value is a number in JavaScript

Check If An Array Includes A Value/Element In Javascript.

Convert String To Float In JavaScript

Combine Multiple Strings Into A Single String | Concatenate Strings

How to compare two strings in JavaScript?