Martin Milo

A blog about software development, architecture, and more.

Weekly updates on latest blog posts, thoughts and useful stuff.

Javascript includes string method

javascript basics

JavaScript includes is a method available on String and Array types. In this short tutorial, I'll show you how to use this method within a String. Long story short, this method simply allows you to check if a specific string is present (part of) another string.

function includes(value: string, position = 0): boolean

// Function params
  // value - is type of string and required
  // position - is optional and fallbacks to 0
// Return value - boolean value (true/false)
const word = 'apple'
const text = 'That three has a lot of apples.'

text.includes(word)
// Output - true
// Why? - because 'apple' is found as a part of text in word 'apples'

The above example is the most common use case for use of includes method on String. But there is an optional param you can pass along the string that you're trying to check.

As you can see, we haven't specified the position. Behind the scenes, the position would just fall back to 0. Let's have a look at a few examples when we specify position.

const word = 'banana'
const text = 'banana is good'
const position = 1

text.includes(word, position)
// Output - false
// Why? - because we start checking text from position 1

What happens is that we're trying to check whether anana is good contains banana. Position represents a number of characters we omit from the left. Keep in mind that whitespace is also considered as a character.

const word = 'orange'
const text = 'Orange is a citrus'

text.includes(word)
// Output - false
// Why? - because orange does not match Orange due to the different casing between o/O

Method returns false due to the different casing between Orange and orange.

Don't forget that an includes String method is case sensitive. It happened to me a few times in my beginnings and cost a lot of frustration when I had to debug my misconceptions.

That's all for this article! I hope you learned something new. Cheers.

Martin Milo
The Author Martin Milo

Seasoned full-stack developer with years of startup experience at Wonderway.io, now focused on BE architecture and DevX at Become1.de. Pragmatic at building own web and native apps. Writing software-related blog posts and teaching.