How do I check for multiple values in a string with JavaScript?

5

To search only for a fixed value in a string I can use the JavaScript function indexOf() , example:

var string = "Oberyn se vinga";
string.indexOf('vinga') >= 0 //retorna true ou false

But how would I do to check multiple values against a string? Example:

var string = "Oberyn se vinga de Sor Clegane";
string.indexOf(['vinga','de','Clegane'])

Apparently the indexOf() function does not accept arrays in the search.

The only way would be to use regex ? Or is there any specific function for these cases?

    
asked by anonymous 05.06.2014 / 19:53

1 answer

5

One way to do this is to use Array.prototype.map to apply indexOf to each array item. For example:

var string = "Oberyn se vinga de Sor Clegane";
var buscar = ['vinga','de','Clegane'];
var indices = buscar.map(String.prototype.indexOf.bind(string));
// [10, 16, 23] 

bind is required for indexOf know in which string it needs to operate. Both bind and map are ECMAScript 5 features, so they will not work on older implementations (such as IE8). But the MDN articles I've listed offer polyfills for these implementations.

    
05.06.2014 / 20:00