onit
onit

Reputation: 2372

How to find text between 2 characters with multiple occurrences?

Given the below string, what would be the most efficient way to get the file ID? The portion wanted: XXXXXXXXXXXxxxxxxxxXXX, which is between / and /view

The attempt below works, but is it really needed to reverse the string twice?

let = url = 'https://drive.google.com/file/d/1pnEX1OXXXXXXu6z9dPV5ZZ5VHqPU--6/view?usp=share_link'

url = reverseString(url)

let id = url.split('weiv/').pop().split('/')[0]
id = reverseString(id)

console.log('URL:' + id)

function reverseString(str) {
  var splitString = str.split("");
  var reverseArray = splitString.reverse();
  var joinArray = reverseArray.join("");
  return joinArray;
}

Upvotes: 1

Views: 53

Answers (3)

Stacks Queue
Stacks Queue

Reputation: 1132

you can use substring to get the value between /d/ and /view

let = url = 'https://drive.google.com/file/d/1pnEX1OXXXXXXu6z9dPV5ZZ5VHqPU--6/view?usp=share_link'

const fileId = url.substring(url.lastIndexOf("/d/") + 3, url.lastIndexOf("/view"));

console.log(fileId)

Upvotes: 1

Dave Pritlove
Dave Pritlove

Reputation: 2687

This solution searches for the "/d/" portion and advances three characters to begin a string.slice, continuing until the next occurence of /. Provided /d/ is always before the id portion, this should be reliable.

const url = 'https://drive.google.com/file/d/1pnEX1OXXXXXXu6z9dPV5ZZ5VHqPU--6/view?usp=share_link';

const id = url.slice(url.indexOf("/d/")+3, url.indexOf("/",url.indexOf("/d/")+3 ));

console.log(id);

Upvotes: 1

Alan
Alan

Reputation: 46813

I'd solve this with a simple regex.

const url = 'https://drive.google.com/file/d/1pnEX1OXXXXXXu6z9dPV5ZZ5VHqPU--6/view?usp=share_link';
const m = url.match(/^.*?\/.\/(.*?)\/view.*$/);
console.log(m[1])

Upvotes: 1

Related Questions