user2915962 user2915962 - 6 months ago 31
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?


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 :)