check if a string contains a substring code example

Example 1: check for substring javascript

const string = "javascript";
const substring = "script";

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

Example 2: check if word is in string javascript

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

Example 3: javascript string contains

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

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

Example 4: javascript string contains function

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

Example 5: .includes( string

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

Example 6: 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))

Tags:

Html Example