Search code examples
javascriptregexurlbookmarklet

Adding text to the beginning of url with JavaScript


I am trying to make a bookmarklet. It should test if the url contains a certain word, if not, it will encode it and add some text to the beginning of the url. So far, I have figured out how to test for the word. The code I am using for that is as follows:

if (document.location.href.indexOf('math') === -1){ 
    alert("Math detected");
}

I want to encode the url like this: If the url it detects is this, http://www.coolmath-games.com/ it should redirect to tunneler.pw/index.php?q=http%3A%2F%2Fwww.coolmath-games.com%2F. Ideally, it wouldn't use regex, but it isn't a big deal if it does.

If it doesn't detect the word, it shouldn't do anything.


EDIT: If anyone was curious, here is the code converted to bookmarklet form.

javascript:void%20function(){-1===document.location.href.indexOf(%22math%22)%26%26alert(%22Math%20detected%22)}();

Solution

  • Try this:

    if (document.location.href.indexOf('blocked') === -1){ 
        document.location.href = "http://tunneler.pw/index.php?q=" + encodeURIComponent(document.location.href);
    }
    

    encodeUriComponent will escape the URL, so you will be able to use it in the query string of another URL.