本人github
JavaScript では、文字列に別の文字列が含まれているかどうかを確認するさまざまな方法があります。
1.String.prototype.includes()
このメソッドは、ある文字列に別の文字列が含まれているかどうかを示すブール値を返します。
const str = "Hello, world!";
const result = str.includes("world"); // 返回 true
2.String.prototype.indexOf()
このメソッドは、文字列内で最初に出現した部分文字列のインデックス位置を表す整数を返します。見つからない場合は -1 を返します。
const str = "Hello, world!";
const result = str.indexOf("world"); // 返回 7
3.String.prototype.search()
このメソッドは正規表現検索を実行し、文字列内で一致した位置を示す整数を返します。見つからない場合は -1 を返します。
const str = "Hello, world!";
const result = str.search("world"); // 返回 7
4. 正規表現
正規表現を使用して、test()
文字列に別の文字列が含まれているかどうかを確認することもできます。
const str = "Hello, world!";
const regex = /world/;
const result = regex.test(str); // 返回 true
これらの方法にはそれぞれ用途と制限があるため、特定のニーズに基づいて最適な方法を選択できます。