CuteMachine

How To Check If A String Is A Substring Of Another String With JavaScript

In this JavaScript article, we will learn how to check whether a string is a substring of another string.

The greatest teacher, failure is.—Yoda

String.includes()

With the includes() method of the String object, you can test whether a substring is included within another string.

const quote = "The greatest teacher, failure is.—Yoda"

quote.includes('Yoda')    // true

If you want to compare without upper and lower case, you should first convert the string to lower case and then search for a lower case substring.

quote.includes('yoda')    // false

quote.toLowerCase().includes('yoda')    // true

String.indexOf()

indexOf() returns -1 if the search string is not included in the string object. Otherwise, the method returns the index where the substring was found.

const quote = "The greatest teacher, failure is.—Yoda"

quote.indexOf('R2D2')    // -1
quote.indexOf('Yoda')    // 34

quote.indexOf('Yoda') === -1 ? false : true    // true

The Lodash includes Function

With Lodash, you can import the includes function. Now that there is a includes() method available in the String object, this solution only makes sense if you are using an older JavaScript version.

import includes from 'lodash/includes'

const quote = "The greatest teacher, failure is.—Yoda"

includes(quote, 'R2D2')    // false
includes(quote, 'Yoda')    // true

startsWith() and endsWith()

If the string starts or ends with the substring, you can use the startsWith() or endsWith() method.

const quote = "The greatest teacher, failure is.—Yoda"

quote.startsWith('The')    // true
quote.endsWith('Yoda')    // true

Regex match()

You can also use a regular expression to search for a substring. To ignore the case, you can append the character i after the regular expression literal.

const quote = "The greatest teacher, failure is.—Yoda"

quote.match(/r2d2/i) ? 'found' : 'not found'    // 'not found'
quote.match(/yoda/i) ? 'found' : 'not found'    // 'found'

Posted on CuteMachine.

Jo's Profile ImageWritten by Jo who lives and works in Frankfurt building digital doodah. Stalk him on Twitter.

TOS • Privacy • Disclaimer