Skip to content

Instantly share code, notes, and snippets.



Last active May 20, 2016
What would you like to do?
Regular Expresion indexOf for Arrays
* Regular Expresion IndexOf for Arrays
* This little addition to the Array prototype will iterate over array
* and return the index of the first element which matches the provided
* regular expresion. Note: This will not match on objects.
* @param {RegEx} rx The regular expression to test with. E.g. /-ba/gim
* @return {Numeric} -1 means not found
if (typeof Array.prototype.reIndexOf === 'undefined') {
Array.prototype.reIndexOf = function (str) {
for (var i in this) {
if (str.toString().match(this[i])) {
return i;
return -1;

This comment has been minimized.

Copy link
Owner Author

@gdibble gdibble commented May 20, 2016

I stopped attaching this to the Array construct.
I now use this as a function rewritten such as the alternate below.

The following alternate-form that lets you pass in strings which become caseInsensitive / globally searched Regular Expressions:

function reIndexOf(array, str) {
  if (str) {
    for (var i in array) {
      if (str.toString().match(new RegExp(array[i], 'ig'))) {
        return i;
  return -1;

Used such as:

var a = [ 'rocks', 'box', 'fox' ];

reIndexOf(a, 'Arctic foxes are common throughout Northern tundra biomes.')

Outputs: 2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment