完全網羅 JavaScriptで文字列が含まれるかどうかの判別方法

はてなブックマーク - 完全網羅 JavaScriptで文字列が含まれるかどうかの判別方法
LINEで送る
Pocket

JavaScriptで文字列が含まれるかどうかの判別方法はいくつかがあります!(6個)

目次

(ES6) String.prototype.includes

var string = "foo",
    substring = "oo";
string.includes(substring);

文字列が検索値を含む場合、true。含まなければ、false

https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/String/includes

ES5 and older String.prototype.indexOf

var string = "foo",
    substring = "oo";
string.indexOf(substring) !== -1;

indexOf() メソッドは大文字と小文字を区別します。

"Blue Whale".indexOf("Blue");     // 0 を返す
"Blue Whale".indexOf("Blute");    // -1 を返す
"Blue Whale".indexOf("Whale", 0); // 5 を返す
"Blue Whale".indexOf("Whale", 5); // 5 を返す
"Blue Whale".indexOf("");         // 0 を返す
"Blue Whale".indexOf("", 9);      // 9 を返す
"Blue Whale".indexOf("", 10);     // 10 を返す
"Blue Whale".indexOf("", 11);     // 10 を返す

https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf

String.prototype.search

var string = "foo",
    expr = /oo/;
string.search(expr);

マッチした場合、文字列内でマッチした箇所のインデックスを返します。マッチしなかった場合は、-1 を返します。

https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/String/search

String.prototype.match

var string = "foo",
    expr = /oo/;
string.match(expr);

https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/String/match

lodash includes

var string = "foo",
    substring = "oo";
_.includes(string, substring);

https://lodash.com/docs#includes

RegExp

var string = "foo",
    expr = /oo/;  // クォーテーションマークはありません
expr.test(string);

https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test

まとめ

これだけで、脳の体操になりますね!

これで一つの文字列がもう一つの文字列に含まれるかどうかを判別したいときはもう悩まないですね!

はてなブックマーク - 完全網羅 JavaScriptで文字列が含まれるかどうかの判別方法
LINEで送る
Pocket

Add a Comment

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close