How to check if a string contains a substring in JavaScript

This tutorial explains how to check if string contains substring using js. this is a common task in work.

There are many ways to do this operation. Usually, I would like to use String.indexOf() method.

If substring not found, it returns -1.

Let's check it out.

String.indexOf()

<script>
var string = "jquerypluginhub-best website for learning js and jquery",
    substring = "website";
if(string.indexOf(substring)>=0){
    //found
}
</script>


Determining if string contains substring example 2 ,using includes.

If substring not found, it returns false.

if(string.includes(substring)){
    //found
}


use search to determining if substring in a string

if(string.search(substring)>=0){
    //found
}


use RegExp to check if a string contains a substring

If substring found, it returns true.

if(expr.test(string)){
    //found
}


use Match to check if string contains substring

it will search for the substring in string and returns a object contains property Index which is the position of the first occurrence of a specified substring.

If substring not found, it returns null.

if(string.match(expr)&&string.match(expr).index>=0){
    //found
}


Sample Code

Change the substring to view the result in different occasions.

<script>
    var string = "jquerypluginhub-best website for learning js and jquery",
        substring = "jquery"; //"oTherStr"
    var expr = /jquery/; 
    console.log(string.indexOf(substring));
    if(string.indexOf(substring)>=0){
        console.log(substring + " is found in "+string);
    }
    console.log(string.includes(substring));
    if(string.includes(substring)){
        console.log(substring + " is found in "+string);
    }
    console.log(string.search(substring));
    if(string.search(substring)>=0){
        console.log(substring + " is found in "+string);
    }
    console.log(expr.test(string));
    if(expr.test(string)){
        console.log(substring + " is found in "+string);
    }
    console.log( string.match(expr))
    if(string.match(expr)&&string.match(expr).index>=0){
        console.log(substring + " is found in "+string);
    }
</script>


date2019-03-23 15:08:17 From:www.jquerypluginhub.com Author:JPH
Related Tags:
Comments

Leave a Reply

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