I have a discussion with another developer about a section of code that had the use of the includes method on a string, and there was some confusion about what it did, and I thought I'd write this full blog post.

The includes() JS method can be used on both strings and arrays, both with slightly different functionality. This post will focus on using it on a string. When using includes on a string it will look for the text you provide inside of a different string.

You can use includes on a string to search through text in the source. Let's start with a variable that's a string:

view plain print about
1let myString = "The Quick Brown Fox Jumped Over The Lazy Dogs"

Now we can use includes to search for other text in that string:

view plain print about
1console.log(myString.includes('Fox')); // returns true

This will output a true since the word Fox is included as part of the full string.

We can also do a full string comparison:

view plain print about
1console.log(myString.includes('The Quick Brown Fox Jumped Over The Lazy Dogs')); // returns true

I do one comparisons here, using a string literal. We can also compare based on a different variable:

view plain print about
1console.log(myString.includes(myString)); // returns true

What happens if you search for something not in the original string? The value will return false:

view plain print about
1console.log(myString.includes('Doggies')); // returns false

The use case for this determine if an Angular interceptor should act on the current URL or not, but there are plenty of other use cases for this.

My next post will talk about how includes works when you use it against an array.

Play with a Plunker here.