LearnFast.Ninja

JavaScript if string contains substring

How to check if string contains substring in JavaScript using indexOf function.

Step 1: Use the index of function. If it not return -1 then your substring found in the original string.
Full_String.indexOf(My_Substring) != -1

Working Example code:

<!DOCTYPE html>

<html>

<head>

    <title>Untitled Page</title>

    <script type="text/javascript">

        var Full_String = "Two things are infinite: the universe and human stupidity; and Im not sure about the the universe.";

        var My_Substring = "not sure about";

        if (Full_String.indexOf(My_Substring) != -1) {

            alert("Contains: " + My_Substring);

        }

    </script>

</head>

 

<body>

</body>

</html>


Results:


Tags

javascript

substring indexof