The greatest teacher, failure is.—Yoda
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
-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
With Lodash, you can import the
includes function. Now that there is a
import includes from 'lodash/includes' const quote = "The greatest teacher, failure is.—Yoda" includes(quote, 'R2D2') // false includes(quote, 'Yoda') // true
If the string starts or ends with the substring, you can use the
const quote = "The greatest teacher, failure is.—Yoda" quote.startsWith('The') // true quote.endsWith('Yoda') // true
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.