Skip to content

Instantly share code, notes, and snippets.

@gdibble
Last active May 20, 2016 22:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gdibble/73821f9eef2d74084a2c to your computer and use it in GitHub Desktop.
Save gdibble/73821f9eef2d74084a2c to your computer and use it in GitHub Desktop.
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;
};
}
@gdibble
Copy link
Author

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