Skip to content

How to check if string contains substring in JavaScript

JavaScript str.indexOf() method, str.includes() str.search() method. How to check if one string contains substring. Javascript string substring check

On this page

The JavaScript indexOf() method search for the substring in string and returns the position of the first occurrence of a specified substring. If substring not found, it returns -1. So you can use JavaScript IndexOf() method to check if a string contains substring in it. In this tutorial we will also provides example to use JavaScript includes() and search() methods to find substring in another string.

In a comparison of all 3 methods describes below, indexOf() can be better due to its speed of execution. If no speed matters, you can use any of the following methods.

Using indexOf() Method

JavaScript indexOf() method will return the starting position number substring in the main string. If substring not found, it will return -1 as a result.

Result will be as below:

 true 

2. Using includes() Method:

Also you could use JavaScript includes() method. It returns true on match found and false if no match found. Use below sample code to test this:

Result will be as below:

 true 

3: Using search() Method

You could also use the JavaScript search() method. It returns string position number if match found. If not match found returns -1.

Result will be as below:

 true 

Rahul

Rahul Kumar is the founder and chief editor of TecAdmin.net. A Red Hat Certified Engineer (RHCE), he has worked in IT since 2009, with hands-on experience in Linux system administration, DevOps, web hosting, cloud platforms and automation. He started TecAdmin in 2013 to share practical, step-by-step guides, and leads its editorial work with one aim: making technical learning clear and useful for sysadmins, developers and beginners alike.

3 Comments

  1. also var expr = “/World/”; is written incorrectly.

    it should have been written var expr = /World/; to achieve the expected results

  2. var result = str.includes(substr) > -1; is written wrong… will return also true when substr is not in str, as false > -1 evaluates to true!!

    should have been written
    var result = str.includes(substr); // result will return true if substr in str, and will return false if not

  3. You can also very easily do this by using this code, implemented in modernizr lib:

    function contains(str, substr) {
    return !!~(” + str).indexOf(substr);
    }

    U can see the full text, docs, usage examples and more at cocycles:

Leave a Reply

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


Back to top