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

Asked

Viewed 1,113 times

3

I need to check if in a String, it contains any words that are in the array.

For example:

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

Would have some more effective and better performing way to do this check, or just using loops to check the vector positions, and comparing with the string?

1 answer

4


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

jsFiddle: https://jsfiddle.net/yjnsoxgm/

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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.