Fraser Hamilton

How to check if a string contains a substring in JavaScript

July 19, 2020

With JavaScript ES6 we can leverage the String.prototype.includes method to check if a substring exists within a string. Here’s an example:

const string = 'Hello World!'
const substring = 'World'

console.log(string.includes(substring))

// true

If you’re working with older browsers such as Internet Explorer support for this method can be spotty. We can instead use String.prototype.indexOf:

var string = 'Hello World!'
var substring = 'World'

console.log(string.indexOf(substring) !== -1)

// true


Written by Fraser Hamilton a full stack developer based out of Edinburgh, Scotland.

© 2020, Fraser Hamilton