2016-05-04 33 views
11

文字列に配列の値の1つが含まれているかどうかを確認する方法はありますか?例えばlodash _.文字列内の複数の値のうちの1つを含む

var text = 'this is some sample text'; 
var values = ['sample', 'anything']; 

_.contains(text, values); // should be true 

var values = ['nope', 'no']; 
_.contains(text, values); // should be false 
+1

あなたはlodash 'values.someことなく、容易にこれを行うことができます(EL => text.indexOf(エル)> -1)'ところで。 – Andy

答えて

2

別の解決策は、すべての値を探しているよりもおそらくより効率的で、値から正規表現を作成することができます。

可能な値を反復すると、テキストの複数の解析が行われますが、正規表現では1つのみで十分です。

function multiIncludes(text, values){ 
 
    var re = new RegExp(values.join('|')); 
 
    return re.test(text); 
 
} 
 

 
document.write(multiIncludes('this is some sample text', 
 
          ['sample', 'anything'])); 
 
document.write('<br />'); 
 
document.write(multiIncludes('this is some sample text', 
 
          ['nope', 'anything']));

制限 このアプローチは、次のいずれかの文字を含む値で失敗します:\^$ * + ? . () | { } [ ](彼らは正規表現構文の一部です)。

これは可能性がある場合は、関連する値(エスケープ)を保護するために(sindresorhusのescape-string-regexpから)次の関数を使用することができます:あなたはすべての可能valuesのためにそれを呼び出す必要がある場合

function escapeRegExp(str) { 
    return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); 
} 

は、しかし、 Array.prototype.someString.prototype.includesの組み合わせがより効率的になる可能性があります(@Andyと他の回答を参照)。

+0

そうですね、正規表現を使うのが一番良い選択だと思います。 – yeouuu

+1

LOL yeaaahhhh regexps ....みんな、あなたの後にあなたの地獄をサポートしなければならないだろう。 –

1

号しかし、これはString.includesを使用して実装が容易です。 You don't need lodash。ここで

だけでこれを行う簡単な関数である:

function multiIncludes(text, values){ 
 
    return values.some(function(val){ 
 
    return text.includes(val); 
 
    }); 
 
} 
 

 
document.write(multiIncludes('this is some sample text', 
 
          ['sample', 'anything'])); 
 
document.write('<br />'); 
 
document.write(multiIncludes('this is some sample text', 
 
          ['nope', 'anything']));

11

使用_.some_.includes

_.some(values, (el) => _.includes(text, el)); 

DEMO

+0

また、良いオプションです。矢印関数のための+1 ;-) – yeouuu

関連する問題