How to determine if it is included (array, string)

There are several ways to determine inclusion. includes, indexOf, test, match, search, etc. are available. Let’s consider which one to use.

TOC

Whether the array contains a specific element or not

The includes and indexOf methods of the Array object are available.

const arr = [40, 30, 20, 10]

if (arr.indexOf(20) !== -1) {
  console.log(arr.indexOf(20))
  console.log('Exists.')
}
if (arr.indexOf(50) === -1) {
  console.log(arr.indexOf(50))
  console.log('Does not exist.')
}

console.log('----------------------------------------')

if (arr.includes(20)) {
  console.log(arr.includes(20))
  console.log('Exists.')
}
if (!arr.includes(50)) {
  console.log(arr.includes(50))
  console.log('Does not exist.')
}
2
Exists.
-1
Does not exist.
----------------------------------------
true
Exists.
false
Does not exist.

The includes method, which returns a Boolean result, is a cleaner way to handle the decision.

includesの注意点

IE11 is not supported. If you want to use it, you need to install babel-polyfil or take other measures.

Whether a specific string is contained in the string or not

Organize how to achieve

This can be accomplished in a variety of ways.

objectmethodRecommendationsupplement
StringindexOf
StringincludesCannot be used in IE11. babel-polyfil must be installed.
StringsearchIt can be done, but not for the original purpose.
StringmatchIt can be done, but not for the original purpose.
RegExptest

Compare indexOf and includes

Compare the decision process between indexOf and includes.

let str1 = 'xxxabcxxx'
let str2 = 'abc'

if (str1.indexOf(str2) !== -1) {
  console.log(str1.indexOf(str2))
  console.log('Exists.')
}

console.log('----------------------------------------')

if (str1.includes(str2)) {
  console.log(str1.includes(str2))
  console.log('Exists.')
}
3
Exists.
----------------------------------------
true
Exists.

The includes method, which returns a Boolean result, is a cleaner way to handle the decision.

Compare includes and test

Compare the decision process for includes and test.

When multiple conditions

let str1 = 'xxxdefxxx'
let str2 = 'abc'
let str3 = 'def'
let regexp = /abc|def/g

if (str1.includes(str2) || str1.includes(str3)) {
  console.log('Exists.')
}

console.log('----------------------------------------')

if (regexp.test(str1)) {
  console.log('Exists.')
}
Exists.
----------------------------------------
Exists.

The test method provides a cleaner decision process.

When you don’t want to be case-sensitive

let str1 = 'xxxABCxxx'
let str2 = 'abc'
let regexp = /abc/ig

console.log(str1.includes(str2))  // false
console.log(regexp.test(str1))    // true

The includes method is case-sensitive. Therefore, if you want to make it case-insensitive, use the test method.

Let's share this post !
TOC