0

I have a variable like,

var url = "/login/user";

And I have an array like,

var x = ["login", "resetpassword", "authenticate"];

Now I need to check, whether that url string is present in an array of string. As we can see that login is present in an array but when i do x.indexOf(url), it always receive false because the field url has rest other letters also. So now how can I ingnore those letters while checking a string in an array and return true?

Chandan Y S
  • 968
  • 11
  • 21

3 Answers3

2

Use .some over the array instead:

var url = "/login/user";
var x = ["login", "resetpassword", "authenticate"];

if (x.some(str => url.includes(str))) {
  console.log('something in X is included in URL');
}

Or, if the substring you're looking for is always between the first two slashes in the url variable, then extract that substring first, and use .includes:

var url = "/login/user";
var x = ["login", "resetpassword", "authenticate"];

var foundStr = url.split('/')[1];

if (x.includes(foundStr)) {
  console.log('something in X is included in URL');
}
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Dupe of https://stackoverflow.com/questions/5582574/how-to-check-if-a-string-contains-text-from-an-array-of-substrings-in-javascript – mplungjan Feb 05 '19 at 09:06
2

One way is to split url with / character and than use some

var url = "/login/user";
var x = ["login", "resetpassword", "authenticate"];

let urlSplitted = url.split('/')

let op = urlSplitted.some(e=> x.includes(e))

console.log(op)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
  • Dupe: https://stackoverflow.com/questions/5582574/how-to-check-if-a-string-contains-text-from-an-array-of-substrings-in-javascript – mplungjan Feb 05 '19 at 09:07
2

You could join the given words with a pipe (as or operator in regex), generate a regular expression and test against the string.

This works as long as you do not have some characters with special meanings.

var url = "/login/user",
    x = ["login", "resetpassword", "authenticate"];

console.log(new RegExp(x.join('|')).test(url));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392