user2915962 user2915962 - 18 days ago 6
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:

https://docs.google.com/spreadsheets/d/1oZK-vdEf2rvBhvAmdrKt1xHNlCehVV-WHDShkZUUaBM/edit#gid=0


The part i'm after is:

1oZK-vdEf2rvBhvAmdrKt1xHNlCehVV-WHDShkZUUaBM


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 = https://docs.google.com/spreadsheets/d/1oZK-vdEf2rvBhvAmdrKt1xHNlCehVV-WHDShkZUUaBM/edit#gid=0;

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
getPosition()
2 times?

Answer

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:

result[4];

Or even:

result.slice(-2)[0];

Using string literals you can short it to:

url.split`/`[4]

Hope it helps :)

Comments