How to check the existence of multiple values in a string with Javascript?

Asked

Viewed 338 times

5

To find only 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 check multiple values against a string? Example:

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

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

The only way would be using regex? Or is there a specific function for these cases?

  • 1

    You want to receive true if at least one of the values was found? Or something more complex (as offset of each value)?

  • @bfavaretto had not assailed me for these two possibilities, but I think the offset of each value would be more interesting, since with it already gives to check if returned something or not.

  • 1

    It is worth noting indexOf() returns the substring index in the original string. Does not return true or false. In fact, in your example the comparison will return false because string.indexOf('vinga') is 10. The ideal comparison would be string.indexOf('vinga') >= 0, for indexOf() will return -1 if it does not find the index. Besides... hey, look at the spoiler, man :P

  • @brandizzi well remembered, corrected there. On the spoiler, it may or may not be, depends on the point of view, haha

1 answer

5


One way to do it is to use Array.prototype.map to apply the indexOf each item in the array. 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] 

The bind is necessary for the indexOf know which string it needs to operate on. Both bind how much map are features of Ecmascript 5, so they will not work in older implementations (such as IE8). But the MDN articles I have indicated offer polyfills for these implementations.

Browser other questions tagged

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