JavaScript

How to check if a string contains a substring in JavaScript

The easiest and fastest way to check if a string contains a substring or not in JavaScript is to use the indexOf() method. This method returns the index or position of the first occurrence of the substring, otherwise, it returns -1 if no match is found.
 

How to check if a string contains a substring in JavaScript using indexOf():
    // Example of a  string
    var str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
    
    // Checks if the substring exists in the string 
    var index = str.indexOf("ipsum"); 
    
    if(index !== -1){
        alert("Substring exists!");
    } else{
        alert("Substring doesn't exists!");
    }

Output:

Substring exists!
 

How to check if a string contains a substring in JavaScript using includes():

In ES6, you can use the includes() method to check whether a string contains a substring or not. This method returns true or false instead of the index. Here is an example:

    // Example of a  string
    var str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
    
    // Checks if the substring exists in the string 
    if(str.includes("ipsum")){
        alert("Substring exists!");
    } else{
        alert("Substring doesn't exists!");
    }

Output:

Substring exists!

 

How to check if a string contains a substring in JavaScript using search():

Also you can use the search() method to search for a particular text or pattern (using a regular expression) within a string. Like the indexOf() method, the search() method also returns the index of the first match, and returns -1 if no match was found.

    // Example of a  string
    var str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
    
    // Checks if the substring exists in the string 
    var index = str.search(/lorem/i); 
    if(index !== -1){
        alert("Substring exists!");
    } else{
        alert("Substring doesn't exists!");
    }

Output:

Substring exists!
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *