The following snippet can be used as a bookmarklet to toggle between multiple websites or pages without typing or even remembering them. Here is the first version, it works fine:
let url;
switch (location.host) {
case 'github.com':
url = location.href;
url = url.replace('github.com', 'stackoverflow.com');
window.open(url, '_self');
break;
case 'stackoverflow.com':
case 'superuser.com':
case 'unix.stackexchange.com':
url = location.href;
url = url.replace('/.+/', 'www.reddit.com');
window.open(url, '_self');
break;
case 'www.reddit.com':
url = location.href;
url = url.replace('www.reddit.com', 'github.com');
window.open(url, '_self');
break;
}
Then I tried to further improve it so that it will work not only for unix.stackexchange
, but also for english.stackexchange.com
, philosophy.stackexchange.com
, bicycles.stackexchange.com
, and so on.
For this, as suggested by T. J. Crowder in his 2010 answer: https://stackoverflow.com/a/2896642, I added regular expressions. But when I try it in the JavaScript console, it throws an error: SyntaxError: Unexpected token '.'. Expected a ')' or a ',' after a parameter declaration.
Why is that, what exactly is wrong here?
function toggle(location.host) {
let url;
switch (true) {
case 'github.com':
url = location.href;
url = url.replace('github.com', 'stackoverflow.com');
window.open(url, '_self');
break;
case 'stackoverflow.com':
case 'superuser.com':
case /.+.stackexchange.com/.toggle(str):
url = location.href;
url = url.replace('/.+/', 'www.reddit.com');
window.open(url, '_self');
break;
case 'www.reddit.com':
url = location.href;
url = url.replace('www.reddit.com', 'github.com');
window.open(url, '_self');
break;
}
}
2
Answers
What may
/.+.stackexchange.com/.toggle(str):
mean? It must indeed throw something, becauseRegExp.toggle
is a non existing method.When you use
switch(true)
you should make sure that everycase
is eithertrue
orfalse
. Otherwise the result will be at least unpredictable. So in your case I suppose you should test a regular expression for each case:The problem exposed in the question is a typo…
The error is caused by this line:
That’s because there is a parameter in the function with a dot (
.
) in the name when they can’t.The following line works just fine:
Or, if you don’t want to let the URL change by the user, then just don’t receive parameters…
Also, there’s this issue with the
.toogle()
that is not aRegExp
method. If you’re trying to make some kind of loop to thetoogle()
function itself, then it’s a very dangerous idea and somewhat complicated to manage (because the function can enter in an infinite loop if not done correctly).There’s this other answer that, although it does not answer your question, gives a working solution to your needs…