How to verify if a string includes a substring in JavaScript?

I would anticipate a method like String.contains(), yet it appears there isn't one available.

What's a good approach to check for this?

1 Like

Hey there! :blush: If you’re working with strings and need to check if one contains another, JavaScript has got some ways to help out! Although there’s no direct String.contains() method, you can make use of includes() or indexOf().

Here’s how you can do it with includes():

const str = "Hello, world!";
const searchTerm = "world";
const result = str.includes(searchTerm); // Returns true if found
console.log(result); // Output: true

Alternatively, using indexOf() is a classic approach:

const str = "Hello, world!";
const searchTerm = "world";
const index = str.indexOf(searchTerm); // Returns the index if found, -1 if not
console.log(index !== -1); // Output: true

Both methods are super handy when I work on string manipulation. Let me know if you need more details or examples! :blush:

Hi! Use includes() for checking if a string contains another:

"Hello, world!".includes("world"); // true

Or use indexOf():

"Hello, world!".indexOf("world") !== -1; // true