Bubble Foundry


regexInArray

by Peter.

Javascript arrays have an inArray() method that tests for the existence of a search object and returns its key. However, sometimes you don’t want to test for an exact match. I wrote a little function that will test a regex instead. Like inArray() it returns -1 if none of the elements satisfy the condition.

function regexInArray(search, arr) {
  for (var k = 0; k < arr.length; k++) {
    if (search.test(arr[k])) {
      return k;
    }
  }
  return -1;
}