I have to return site type (business or personal) value from page path
The function I use is:
function currentPath() {
var siteType=window.location.pathname;
if ( siteType.indexOf('business')) {
siteType= 'business';
} else {
siteType = 'personal';
}
return siteType;
}
So if page path contains "business", it should return business and if it does not contain "business" it should return "personal".
CodePudding user response:
function currentPath() {
var siteType=window.location.pathname;
if ( siteType.indexOf('business') !== -1) { //return -1 if not present
siteType= 'business';
} else {
siteType = 'personal';
}
return siteType;
}
or
function currentPath() {
var siteType=window.location.pathname;
if (siteType.includes('business')) { //checks for the string in the given string or array
siteType= 'business';
} else {
siteType = 'personal';
}
return siteType;
}
CodePudding user response:
You can use includes()
method with conditional operator:
function currentPath() {
return window.location.pathname.includes('business') ? 'business' : 'personal';
}
CodePudding user response:
If you're using indexOf
in a if/else condition you need to check the index so you can proceed if (siteType.indexOf('business') > -1)...
for example.
Modern JS allows us to use includes
, and a little destructuring.
function currentPath() {
const { pathname } = window.location;
if (pathname.includes('business')) return 'business';
return 'personal';
}
CodePudding user response:
Use includes()
function currentPath() {
var siteType = window.location.pathname;
if (siteType.includes('business')) {
return 'business';
} else {
return 'personal';
}
}