# How to check if a string contains a substring in JavaScript

> Learn how to check if a string contains a substring in JavaScript, the modern way with the includes() method, or the pre-ES6 way with indexOf() and !== -1.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2018-05-01 | Updated: 2019-05-30 | Topics: [JavaScript](https://flaviocopes.com/tags/js/) | Canonical: https://flaviocopes.com/how-to-string-contains-substring-javascript/

Checking if a string contains a substring is one of the most common tasks in any programming language.

[JavaScript](https://flaviocopes.com/javascript/) offers different ways to perform this operation.

The most simple one, and also the canonical one going forward, is using the `includes()` method on a string:

```js
'a nice string'.includes('nice') //true
```

This method was introduced in [ES6/ES2015](https://flaviocopes.com/es6/).

It's supported in all modern browsers except Internet Explorer:

![Browser Support for includes](https://flaviocopes.com/images/how-to-string-contains-substring-javascript/browser-support-includes.png)

To use it on all browsers, use [Polyfill.io](https://polyfill.io/) or another dedicated polyfill.

`includes()` also accepts an optional second parameter, an integer which indicates the position where to start searching for:

```js
'a nice string'.includes('nice') //true
'a nice string'.includes('nice', 3) //false
'a nice string'.includes('nice', 2) //true
```

## Pre-ES6 alternative to includes(): `indexOf()`

Pre-ES6, the common way to check if a string contains a substring was to use `indexOf`, which is a string method that return -1 if the string does not contain the substring. If the substring is found, it returns the index of the character that starts the string.

Like `includes()`, the second parameters sets the starting point:

```js
'a nice string'.indexOf('nice') !== -1 //true
'a nice string'.indexOf('nice', 3) !== -1 //false
'a nice string'.indexOf('nice', 2) !== -1 //true
```
