DEV Community

Cover image for How to search for a string inside a string in JavaScript?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to search for a string inside a string in JavaScript?

Originally posted here!

To search for a string inside another string, you can use the includes() method on the string in JavaScript.

Let's say you have a string called Hello ๐Ÿ˜ƒ, How are you?

// a string
const str = "Hello ๐Ÿ˜ƒ, How are you?";
Enter fullscreen mode Exit fullscreen mode

And now let's check whether the above string contains the word How. So let's use the includes() method on the str to check that.

// a string
const str = "Hello ๐Ÿ˜ƒ, How are you?";

// check if How is present in str
const isPresent = str.includes("How");

console.log(isPresent); // true
Enter fullscreen mode Exit fullscreen mode

The includes() method accepts:

  • a string to search for as the first argument
  • an optional position of type number to start searching from that position
  • the method returns boolean true is the string present and false if not.

See this example live in JSBin.

Feel free to share if you found this useful ๐Ÿ˜ƒ.


Top comments (0)