I am using indexOf function to check whether specific string exist in the given array or not but It is giving me "-1" always even though specific string exist in given array. Below is code for same.
var independentLocations = ['/home', '/login','/ImpersonateUser'];
independentLocations.indexOf("/Authorization/ImpersonateUser");
Above code giving result "-1" each time even though "ImpersonateUser" is available in given array.
Please help me in this.
>Solution :
Use Array.prototype.findIndex in combination with:
String.prototype.includes (bug-prone solution) :
const independentLocations = ['/home', '/login','/ImpersonateUser'];
const path = "/Authorization/ImpersonateUser";
const idx = independentLocations.findIndex(x => path.includes(x));
console.log(idx); // 2
Notice: that’s the simplest but might be bug-prone: for example, if you use i.e: "/Authorization/ImpersonateUsers" (notice the "s") it will still retun a matching index.
to make it more precise you might use RegExp.prototype.test():
const independentLocations = ['/home', '/login','/ImpersonateUser'];
const path = "/Authorization/ImpersonateUser";
const idx = independentLocations.findIndex(x => new RegExp(`\\b${x}\\b`).test(path));
console.log(idx); // 2