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:
Now we can use includes to search for other text in that string:
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:
I do one comparisons here, using a string literal. We can also compare based on a different variable:
What happens if you search for something not in the original string? The value will return 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.