Javascript: Find index of slash (/) in a string

I don't know much about javascript (only done JAVA) but that havent keept me from doing a hack on some javascript code I found (from Google Bookmarks).

Here is my case: I'm creating a bookmark in my browser that contains a javascript instead of a URL link. When I press the bookmark I want it to open a new window with the same url but with some extra info. So say Im on and I press the bookmark, then it should open a window with the link: - so ".DoYou" have been inserted just before the 3th "/"

I have the following script:

    var a=window, b=document, c=encodeURIComponent,
    url = b.location,
    d =, "bkmk_popup", "left="+
    ",height=600px, width=1200px, resizable=1, alwaysRaised=1");

So far it opens a window with the same url. But I can't seem to split the url at the 3th "/". Have tried to get the index of the backslash in order to split the url and insert ".DoYou"

 i = url.indexOf("//",9)

but then the window will not open. Please help me out!


javascript:( function(){ 
    var a=window;
    url = b.location; 
    var parts = window.location.href.split("/");
    parts[2] += ".DoYou";
    var newurl = parts.join("/");, "bkmk_popup","left="+((a.screenX||a.screenLeft)+50)+",top="+((a.screenY||a.screenTop)+50)+",height=600px,width=1200px,resizable=1,alwaysRaised=1"); a.setTimeout(function(){d.focus()},300);

It can be done with a simple reg exp, using the parts of the window.location object [host/search/etc] or a simple split and join.

Here is the simple split and join solution.

var parts = window.location.href.split("/");
parts[2] += ".DOYOU";
var newStr = parts.join("/");

You don't need to escape the / (forward slash).

i = url.indexOf("/",9)

P.S. The escape character is usually a backslash (\).

In a similar way to the accepted answer, if you don't really need to find the index, but want to place something near it, you can use string.replace(replacedtext, newtext) and RegEx.

For your URL example, if you wanted to add text before the first slash with word characters on either side, you could do

url = url.replace(/(\w(?=\/\w))/, '$1' + '.DoYou');

The $1 inserts the 1st parenthesized submatch string (see here for more explanation of the $).


Like your issue, I wanted to do the same thing except in the same window, so I did:


Having this as a bookmark allows me to just click the bookmark and take me to the page I want.