LoginSignup
1
2

More than 5 years have passed since last update.

[JavaScript] String#contains で正規表現マッチができればいいのに

Last updated at Posted at 2015-03-01

RegExp#test はあるけど、文字列レシーバで単純正規表現テストしたいなー

え? String#search があるって? Boolean 返してくれよ

ということで String#contains に上書き実装

(function(){
  let _contains = String.prototype.contains;
  Object.defineProperty(String.prototype, 'contains', {
    enumerable: false,
    configurable: true,
    writable: true,
    value: function contains(...args){
      let [searchString, position] = args;
      if(searchString != undefined && searchString.constructor === RegExp){
        return searchString.test(this.slice(position));
      }else{
        return _contains.call(this, ...args);
      }
    },
  });
})();
example
'foo'.contains('o'); //=> true
'foo'.contains(/o/); //=> true
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2