Use an array of regular expressions instead - and use actual regular expressions if you want to perform regex tests, not strings.
Also, I'm pretty that
".*loan. *"
and
". *reward.*"
are typos - if you just wanted to match any string with loan and reward in them, just use the regular expression /loan/ or /reward/.. (Your first loan will match loan followed by any character, followed by zero or more spaces. Your reward will match any character, followed by zero or more spaces, followed by reward. That doesn't sound like what you need.
const patterns = [
[/product/, 'productDetail'],
[/login/, 'login'],
[/loan/, 'loanDetail'],
[/^(?!.* (product|login|loan reward)). *$/, 'uncategorized'],
];
const pageTypeArray = [];
const { href } = window.location;
for (const pattern of patterns) {
if (pattern[0].test(href)) {
pageTypeArray.push(pattern[1]);
}
}
loan reward in your original code may be a typo too - did you mean to put a | between those? If so - if uncategorized is meant to exist when nothing else matches - then ditch the regular expressions entirely and just use String#includes:
const patterns = [
['product', 'productDetail'],
['login', 'login'],
['loan', 'loanDetail'],
];
const pageTypeArray = [];
const { href } = window.location;
for (const pattern of patterns) {
if (href.includes(pattern[0])) {
pageTypeArray.push(pattern[1]);
}
}
if (pageTypeArray.length === 0) {
pageTypeArray.push('uncategorized');
}