2
var pathname = window.location.pathname;
if (! (pathname.indexOf('edit') > -1) ) {
  // Do stuff...
}

In the above example I am negating and only running the JS on pages that DO NOT include 'edit', I want to change it to accept multiple arguments, for example, "edit", "delete", "admin", "settings".

Whats the best way of doing this?

Collins
  • 1,069
  • 14
  • 35

4 Answers4

4
var pathname = window.location.pathname;

if (["edit", "delete", "admin"].some(x => pathname.indexOf(x) > -1)) {
    // ...
}

Without arrow function for older browsers

var pathname = window.location.pathname,
    isSpecialPath = ["edit", "delete", "admin"].some(function(x) { return pathname.indexOf(x) > -1; });

if (isSpecialPath) {
    // ...
}

Array.prototype.some(): The some() method tests whether some element in the array passes the test implemented by the provided function.

Andreas
  • 21,535
  • 7
  • 47
  • 56
1

You can make a loop an see if anything is found and do what you want afterwards.

var pathname = window.location.pathname;
var names = ["edit", "delete", "admin", "settings"];
var found = false;

for( var i = 0; i < names.length; i++ ) {
    if( pathname.indexOf(names[i]) > -1 ) {
        found = true;
        break;
    }
}

if( !found ) {
    // do stuff
}
eisbehr
  • 12,243
  • 7
  • 38
  • 63
0

You can use a regular expression to test for multiple values, eg:

var pathname = window.location.pathname;

var textToSearchFor = /(edit)|(delete)|(ADDMORE)/;

if (path.match(textToSearchFor) == null) {
  //Entered Text not available
  //alert("Not available");
}
else {
   //Entered Text available
   //alert("Available");
}

Reference : How to search for multiple texts in a string, using java script?

Community
  • 1
  • 1
0

You can try with this :

var pathname = window.location.pathname;
if((/edit|delete|admin|settings/i).test(pathname))
{
    console.log("exists");
}
else
{
    console.log("not exists");
}
KavitaP
  • 61
  • 5