Skip to content

Instantly share code, notes, and snippets.

@think49
Last active January 31, 2017 17:53
Show Gist options
  • Save think49/811ac93dae801a4cec2e58a70a9b961a to your computer and use it in GitHub Desktop.
Save think49/811ac93dae801a4cec2e58a70a9b961a to your computer and use it in GitHub Desktop.
array-findwordall.js: 配列から指定した文字列リスト全てを含む要素を抽出します (要ES5)

array-findwordall.js

概要

配列から指定した文字列リスト全てを含む要素を抽出します。

使い方

第一引数で指定した配列の内、第二引数で指定した配列の全ての文字列を含む要素を抽出します。

findWordAll(['foo', 'bar', 'piyo', 'foobar', 'bar-foo', 'foo-bar'], ['foo', 'bar']); // ["foobar", "bar-foo", "foo-bar"]

内部的に正規表現を利用しており、第三引数で正規表現フラグを指定する事が可能です。

findWordAll(['foo', 'bar', 'piyo', 'foobar', 'FooBar', 'BAR-FOO'], ['foo', 'bar'], 'i'); // ["foobar", "FooBar", "BAR-FOO"]
/**
* array-findwordall.js
*
* @version 1.0.0
* @author think49
* @url https://gist.github.com/think49/811ac93dae801a4cec2e58a70a9b961a
* @license http://www.opensource.org/licenses/mit-license.php (The MIT License)
*/
var findWordAll = (function (RegExp, call, test, replace) {
function mapfn (string) {
return '(?=[\\s\\S]*' + replace(string, /(?=[$()*+\-.?\[\]^{|}])/g, '\\') + ')';
}
return function findWordAll (array, searchWords /* [, flag]*/) {
return array.filter(call.bind(test, new RegExp('^' + searchWords.map(mapfn).join(''), arguments[2])));
};
}(RegExp, Function.prototype.call, RegExp.prototype.test, Function.prototype.call.bind(String.prototype.replace)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment