user2915962 user2915962 - 1 year ago 60
Javascript Question

Substring between 2 known chars

Im looking for a quick and inexpensive way to get a substring from a url looking like this:

The part i'm after is:


So we know that we want the value between the 4th '/' and the 5th '/' (zerobased index).

One solution could be something like:

function getPosition(str, m, i) {
return str.split(m, i).join(m).length;

var url =;

var firstOccurence = getPosition(url,'/',4);
var secondOccurence = getPosition(url,'/',5);

var result = url.substring(firstOccurence, secondOccurence);

Any tips om improvemnets? Could this be made without having to call
2 times?

Answer Source

You can use the split method from String:

var result = url.split('/');

It will return an array, you can access the part you want by index:


Or even:


Using string literals you can short it to:


Hope it helps :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download