Javascript for conditional URL append or redirect based on window.location.href

Posted by Wintermute on Stack Overflow See other posts from Stack Overflow or by Wintermute
Published on 2010-04-05T08:19:01Z Indexed on 2010/04/05 8:23 UTC
Read the original article Hit count: 313

::Hi all::

I am trying to make a bookmarklet that when clicked will check the URL of the current tab\window to see if it contains 'char1' and\or 'char2' (a given character). If both chars are present it redirects to another URL, for the other two it will append the current URL respectively.

I believe there must be a more elegant way of stating this than the following (which has so far worked perfectly for me) but I don't have great knowledge of Javascript. My (unwieldy & repetitive) working code (apologies):

if (window.location.href.indexOf('char1')!=-1 && window.location.href.indexOf('char2')!=-1) {window.location="https://website.com/";} else if (window.location.href.indexOf('char1')!=-1) {window.location.assign(window.location.href+='append1');} else if (window.location.href.indexOf('char2')!=-1) {window.location.assign(window.location.href+='append2');}

Does exactly what I need it to but, well... not very graceful to say the least.

Is there a simpler way to do this, perhaps with vars or a pseudo-object? Or better code :D

© Stack Overflow or respective owner

Related posts about bookmarklet

Related posts about JavaScript