javascript ES6時代の文字列比較

いつの間にか、startsWithやendsWithが追加されている。
正規表現
String.match(/^比較文字列/)
String.match(/比較文字列$/)
でもいいけど、気持ち的に処理が重くない方がいいかな。

最近のchromeとかでは部分一致のincludesも追加されている。
chrome拡張とかでは使ってもいいと思う。

なければ ~String.IndexOfで代用

完全一致

 String === '比較文字列'

厳密比較演算子を使用する。

そうでないと文字列のつもりが数値で0が入ったときに
以下の比較はtrueになる。

 0 == ''

前方一致

 String.startsWith('比較文字列')

後方一致

 String.endsWith('比較文字列')

部分一致

 String.includes('比較文字列')

※ 旧メソッド名 contains
なければ

 ~String.indexOf('比較文字列')

正規表現

 String.match(/正規表現/)

最近、ぐぐっても、古い記事ばかりで、実は既に実装済みだったのに、車輪の再発明しちゃったってことになりがちなので、まずは欲しい機能がすでに実装されてないかMDNを確認しよう。

MDNでは、prototypeも公開されているので、実装されてないブラウザでも関数を実装しておくと何かと便利。

  • startsWith
if (!String.prototype.startsWith) {
  String.prototype.startsWith = function(searchString, position) {
    position = position || 0;
    return this.lastIndexOf(searchString, position) === position;
  };
}
  • endsWith
if (!String.prototype.endsWith) {
    Object.defineProperty(String.prototype, 'endsWith', {
        enumerable: false,
        configurable: false,
        writable: false,
        value: function (searchString, position) {
            position = position || this.length;
            position = position - searchString.length;
            return this.lastIndexOf(searchString) === position;
        }
    });
}
  • includes MDNになかったの適当に作った物、不備があるかも
if (!String.prototype.includes) {
  String.prototype.includes = function(searchString) {
    return ~this.indexOf(searchString);
  };
}