Skip to content

JavaScript string contains substring or characters | include function

  • by

Using the includes() function you can check whether a string contains a substring in JavaScript. This method returns true if the string contains the characters, and false if not.

Usually, programmers would expect a String.contains() method, but there doesn’t exist in JS.

Syntax

string.includes(subString, start)

Examples of the JavaScript string contains a substring

Let’s see multiple examples.

if the string contains

<!DOCTYPE html>
<html>
  <head>
    <script>

    	var str = "Hello world, welcome to the universe.";
		var n = str.includes("world");
		alert(n)

    </script>
  </head>   

</html>

Output:

JavaScript string contains substring or characters

Check javascript string contains a character

Let’s find “hello” in your_string using a indexOf() method in JS.

if (your_string.indexOf('hello') > -1)
{
  alert("hello found inside your_string");
}

The string contains case insensitive in JS

Add .toLowerCase() after referrer. This method turns the string into a lower case string. Then, use includes() function.

Check below code for it:-

if (referrer.toLowerCase().includes(someString.toLowerCase())) { ... }

Do comment if you know other ways and have any doubts.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version

Leave a Reply

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