Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

IndexOf function is always returing -1

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading