string has substring code example

Example 1: angular string contains

const string = "foo";
const substring = "oo";

console.log(string.includes(substring));

Example 2: javascript string contains

var string = "foo",
    substring = "oo";

console.log(string.includes(substring));

Example 3: javascript string contains function

s = "Hello world";
console.log(s.includes("world"));

Example 4: check if string contains substring

Like this:

if (str.indexOf("Yes") >= 0)
...or you can use the tilde operator:

if (~str.indexOf("Yes"))
This works because indexOf() returns -1 if the string wasn't found at all.

Note that this is case-sensitive.
If you want a case-insensitive search, you can write

if (str.toLowerCase().indexOf("yes") >= 0)
Or:

if (/yes/i.test(str))

Example 5: how to check if a string contains a character

public static boolean containsIgnoreCase(String str, char c) {
        str = str.toLowerCase();

        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == Character.toLowerCase(c)) {
                return true;
            }
        }
        
        return false;
    }

Tags:

Misc Example