How to check if String is contained in a position of an array?

3

I need to check if in a String, it contains some word that is in the array.

For example:

var array = ['faço?', '**fazer**' ]
var str = 'como eu posso **fazer** isso?' 

Would there be a more effective and better performing way of doing this check, or just using loops to check vector positions, and comparing with the string?

    
asked by anonymous 11.05.2016 / 20:04

1 answer

4

For a simple check you can do this:

var existem = ['faço?', 'fazer' ].filter(function(palavra{
    return str.indexOf(palavra) != -1;
});

And if the array existem has length > 0 it is because there are words from the array in the string and they will be inside that array. This method is simple and gives positive in the case of the phrase you indicated but also in the case of:

  

"I'm going to do the suitcase now."

But in this case it may be a false positive. To correct this you can do this:

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 "[]"

jsFiddle: link

If you only want true or false and you do not need to know what words can check positive then as @BrunoBR suggested you can use .some() like this:

function palavras(str, arr) {
    return arr.some(function(palavra) {
        var regex = new RegExp('\s' + palavra + '[\s,\.\?\!]');
        return str.match(regex);
    });
}

jsFiddle: link

.some() has the great advantage of stopping searching as soon as the first positive is found, saving the processor.

    
11.05.2016 / 20:57