Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
63
rated 0 times [  67] [ 4]  / answers: 1 / hits: 27178  / 7 Years ago, wed, february 22, 2017, 12:00:00

My url looks like this = https://studentscafe.com/menu/2



I'm trying to check whether or not it has 2 different url params...



1.) ?dinner=1



or



2.) &dinner=1



If #1 is present, do nothing



If #2 is present, do nothing



But if neither are present, default to adding ?dinner=1 to the url.



Is there a better way to have a default do nothing in an if statement? Fiddle here for example.



var path = 'https://studentscafe.com/menu/2';

if (path.indexOf('?dinner=1') >= 1) {
console.log('has ?');
// do nothing leave url as it is

} else {
console.log('does not have ?');
if (path.indexOf('&dinner=1') >= 1) {
// do nothing leave url as it is
} else {
path = path + '?dinner=1';
}
}


Expected output: if the url doesn't have #1 or #2: https://studentscafe.com/menu/2?dinner=1


More From » javascript

 Answers
133

Using a regular expression and the ! negation operator, this can be rather simple:





var path = 'https://studentscafe.com/menu/2';

if (!/[?&]dinner=1/.test(path)) {
path += '?dinner=1';
}

console.log(path);




[#58818] Tuesday, February 21, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jarrettw

Total Points: 300
Total Questions: 98
Total Answers: 103

Location: Saudi Arabia
Member since Mon, Sep 5, 2022
2 Years ago
;