Reputation: 2711
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?
Upvotes: 1
Views: 59
Reputation: 4365
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 :)
Upvotes: 5
Reputation: 8695
You can use regex:
var url = 'https://docs.google.com/spreadsheets/d/1oZK-vdEf2rvBhvAmdrKt1xHNlCehVV-WHDShkZUUaBM/edit#gid=0';
var result = url.match(/spreadsheets\/d\/([^\/]+)\/?/);
if(result){
console.log(result[1])
}
Upvotes: 1
Reputation:
var url = 'https://docs.google.com/spreadsheets/d/1oZK-vdEf2rvBhvAmdrKt1xHNlCehVV-WHDShkZUUaBM/edit#gid=0';
var part = url.replace('https://', '').split(/\//g)[3]
console.log(part)
Upvotes: 0