0

I'm trying to dynamically show or hide an element based on the current site title. There are more than 4 pages but only using 4 as an example:

var stringTitle = window.location.pathname; 
var home1 = "/sites/xxx/pages/home.aspx";
var home2 = "/sites/xxx/employees/pages/home.aspx";
var home3 = "/sites/xxx/directory/pages/home.aspx";
var home4 = "/sites/xxx/forms/pages/home.aspx";

if (stringTitle == home1 || stringTitle == home2 || stringTitle == home3) {
    //Display Something
}

Since this could potentially be really long, is there a way I can use variables in array then use it in If statement? I tried the following but didn't work and also found out includes() doesn't work in IE:

var hmArray = [home1, home2, home3, ...];
var n = hmArray.includes(stringTitle); //true or false
if (n == 1) {
  //display stuff
}
2

2 Answers 2

1

You could use indexOf();

if (hmArray.indexOf(stringTitle) !== -1) {
  // display stuff
}
Sign up to request clarification or add additional context in comments.

1 Comment

I tried indexOf before but I thought it didn't work -- found out in dev tools that Chrome was not displaying the changes made -- it took few refresh / clear cache to apply the changes. Thanks
0

You could make a polyfill for includes if you wanted.

Array.prototype.includes = Array.prototype.includes || function(value){
    return this.indexOf(value) > -1;
};

Then the browsers that have contains would use the native one, and those that don't would use yours.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.