For a simple check you can do so:
var existem = ['faço?', 'fazer' ].filter(function(palavra{
return str.indexOf(palavra) != -1;
});
What if the array existem
has length > 0
is because there are words from the array in the string and they will be inside that array. This method is simple and positive in the case of the sentence you have indicated but also in the case of:
"I’mdo the suitcase now."
but in this case maybe it’s a false positive... to fix it you can do so:
var filtros = ['faço?', 'fazer'];
function palavras(str, arr) {
var existem = arr.filter(function(palavra) {
var regex = new RegExp('\\s' + palavra + '[\\s,\\.\\?\\!]');
return str.match(regex);
});
return existem;
}
var testeA = palavras('como eu posso fazer isso?', filtros);
var testeB = palavras('Vou desfazer a mala agora.', filtros);
console.log(testeA.length > 0, JSON.stringify(testeA)); // dá: true "["fazer"]"
console.log(testeB.length > 0, JSON.stringify(testeB)); // dá: false "[]"
If you just want to true
or false
and you don’t need to know which words can check positive then, as @Brunobr suggested you can use the .some()
thus:
function palavras(str, arr) {
return arr.some(function(palavra) {
var regex = new RegExp('\\s' + palavra + '[\\s,\\.\\?\\!]');
return str.match(regex);
});
}
jsFiddle: https://jsfiddle.net/yjnsoxgm/1/
The .some()
has the great advantage of stopping searching as soon as the first positive is found, saving the processor.