Check if a string contains another substring


Problem

There's a rather frequent need to figure out whether a string is contained in another string. There are many ways to achieve that, also depending on the version of JavaScript you are using.



Solution

The oldest solution is probably indexOf of which exists since the first version of JavaScript. The details can be found on the great Mozilla Developer Network https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf.

var input = 'this is something useless'
var result = input.indexOf('useless') !== -1
// result will be true in case the string in the first parameter is contained in the input string

The same can be achieve by using Regex, but it's a bit slower than indexOf, here's the full example

var input = 'this is something useless'
var result = input.search(/useless/) !== -1
// result will be true in case the string in the first parameter is contained in the input string

Or in case you are using EcmaScript6, in short ES6, you can also use includes. The complete definition https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes and here a simple example:

var input = 'this is something useless'
var result = input.includes('useless')

Comments




Please sign-in to post a comment