OMcRey
OMcRey

Reputation: 23

Find index number of array value based on partial string match

I have been stuck on this as I am not the best with mixing arrays + string matches.

What I would like to do is return the index number within an array based on a partial match from a string. Full use case; check if text exists in a URL based off values within an array - and return the index of array position.

Don't mind JS or jQuery but whichever might be most efficient is fine (or works).

Current attempt:

Example URL = www.site.com/something/car/123

Another Example URL might be www.site.com/something/somethingelse/banana/

(location of snippet to match is not always in the same path location)

var pageURL = location.href;
var urlArray = ['/car/','/boat/','/apple/','/banana/'];
function contains(urlArray, value) {
var i = urlArray.length;
while (i--) { if (urlArray[i].indexOf(pageURL)) console.log(i)} console.log('Not Found');}

alternate Using jQuery (not sure where to use indexOf or another jQuery alternative (.search / .contains)):

urlArray.each(function(){
$.each(this, function(index) { } )   });

Expected output for first URL would be 0, second example URL would be 3.

Help is much appreciated!

Upvotes: 1

Views: 6865

Answers (3)

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

You can also use a forEach() loop on the urlArray to get each word from the array and check if it exist in url or not.

var url = 'www.site.com/car/somethingelse/banana/';
var urlArray = ['/car/', '/boat/', '/apple/', '/banana/'];
urlArray.forEach(function(word){
  //if word exist in url
  var wordIndex = url.indexOf(word);
  if(wordIndex !== -1){
    console.log(wordIndex);
  }
});

NOTE includes() do not work in IE browser and older versions thus to make it work on all browsers the recommended way is to avoid arrow functions with includes() and instead use plain function with indexOf()

To return the array index:

var url = 'www.site.com/car/somethingelse/banana/';
var urlArray = ['/car/', '/boat/', '/apple/', '/banana/'];
urlArray.forEach(function(word, index){
  //if word exist in url
  if(url.indexOf(word) !== -1){
    console.log(index);
  }
});

Upvotes: 2

Omar
Omar

Reputation: 98

for (var i = 0; i < urlArray.length; i++) {
 if(pageURL .indexOf(urlArray[i])>-1){
   console.log(pageURL.indexOf(urlArray[i])));
 } 
}

Upvotes: 0

Mark
Mark

Reputation: 92450

You can iterate over the array with findIndex() to get the index if the includes() the string.

This will go through the urlArray and return the index of the first match (and -1 if a match isn't found).

let URL1 = "www.site.com/something/car/123"
let URL2 = "www.site.com/something/somethingelse/banana/"

let urlArray = ['/car/','/boat/','/apple/','/banana/'];

let index1 = urlArray.findIndex(str => URL1.includes(str))
let index2 = urlArray.findIndex(str => URL2.includes(str))

console.log(index1, index2)

Upvotes: 2

Related Questions