JavaScriptで存在チェック(〜を含む)を書く機会があったので、メモ。
変数
変数宣言
const string = "abcdefg";
match
/* match
文字列が含まれれば配列、文字列が含まれなければnullが返る
console.log(string.match(/abc/)) => (1) ["abc"]
console.log(string.match(/hoge/)) => null
*/
console.log(string.match(/abc/));
// => true
match(//)
の部分は、変数ではなくてstring
として認識されるので、変数を使いたい場合は、「正規表現オブジェクト」を使う。
RegExpオブジェクト
const target = "a";
const reg = new RegExp(target, "ig");
console.log(string.match(reg));
// => (1) ["a"]
console.log(reg.test(string));
// => true
RegExp オブジェクトのコンストラクタ関数を呼び出して 正規表現を記述
RegExpの第二引数にあるi
とg
は検索パターンのオプション。
-
g
マッチしたもの全てを返す -
i
大文字と小文字を区別しない
結果のコメントを見てもわかるように、 match
とtest
では返ってくる値が違います。単純に、値を含むかどうかを調べるには、test
を使うといいのかも。
indexOf
const target = "a";
console.log(string.indexOf(target) != -1);
// => true
indexOf
文字列が見つかれば文字列が見つかった場所が。
文字列が見つからなければ-1が返ってくる
/*
console.log(string.indexOf('hoge')) => -1
console.log(string.indexOf('世界')) => 5
*/
配列
配列を定義
const array = ["abc", "def", "ghi", "jk", "lmn", "opqr", "stu"];
indexOf
const target = "ghi";
console.log(array.indexOf(target))
// => 2
console.log(array.indexOf(target) !== -1)
// => true
文字列と一緒で、
配列の場合、一致するindex を返す
見つからなければ、-1が返ってくる
includes
const target = "ghi";
console.log(array.includes(target));
// => true
includes
特定の要素が配列に含まれているかどうか
some
const target = "abc";
console.log(array.some((c) => c === target));
// => true
Array.some
と Array.includes
の違いはこちらの記事がわかりやすかったです。
オブジェクト配列
const arrayOject = [
{
id: 1,
name: "abc",
description: "abc",
price: 1000
},
{
id: 2,
name: "def",
description: "def",
price: 3000
},
{
id: 3,
name: "ghi",
description: "ghi",
price: 2000
}
];
some
console.log(
arrayOject.some((c) => c.name === target)
);
// => true
findIndex
// findIndex
console.log(
arrayOject.findIndex((c) => c.name === target) != -1
);
// => true