split variables from array

Viewed 41

I have an array of urls that get pulled in with "videoJsonUrl" and i'm trying to get a variable from the urls that come in _id=XXXXXXXX this is what I have so far, which works if I add the url in it manually:

const VideoUrl = "https://player.vimeo.com/external/444937644.sd.mp4?s=a6aa1fdd06df967a0cfc300dbfef1a24927e4f61&profile_id=165&oauth2_token_id=57447761"
const strs = VideoUrl.split('_id=');
const videoId = strs.at(-1)
console.log("Get Content Video ID",videoId);

I cant for the life of me get it to work "videoJsonUrl" though, I think the problem is that "videoJsonUrl" actually contains 3 urls, like this:

enter image description here

can anyone give me any pointers on how to do it?

3 Answers

You can construct a new URL object from each address, then use its searchParams property to get the parameter value of interest:

const urls = [
  'https://player.vimeo.com/external/444937644.sd.mp4?s=a6aa1fdd06df967a0cfc300dbfef1a24927e4f61&profile_id=165&oauth2_token_id=57447761',
  'https://player.vimeo.com/external/444937644.sd.mp4?s=a6aa1fdd06df967a0cfc300dbfef1a24927e4f61&profile_id=165&oauth2_token_id=57447823',
  'https://player.vimeo.com/external/444937644.sd.mp4?s=a6aa1fdd06df967a0cfc300dbfef1a24927e4f61&profile_id=165&oauth2_token_id=57447915',
];

const results = urls.map(url => {
  const id = new URL(url).searchParams.get('oauth2_token_id');
  return id;
});

console.log(results); // [ "57447761", "57447823", "57447915" ]

URLSearchParams instances have a built-in entries iterator so this should also be fine:

    const urls = [
    'https://player.vimeo.com/external/444937644.sd.mp4?s=a6aa1fdd06df967a0cfc300dbfef1a24927e4f61&profile_id=165&oauth2_token_id=57447761',
    'https://player.vimeo.com/external/444937644.sd.mp4?s=a6aa1fdd06df967a0cfc300dbfef1a24927e4f61&profile_id=165&oauth2_token_id=57447823',
    'https://player.vimeo.com/external/444937644.sd.mp4?s=a6aa1fdd06df967a0cfc300dbfef1a24927e4f61&profile_id=165&oauth2_token_id=57447915',
  ];
  
const results = urls.map(url => {
    const { oauth2_token_id } = Object.fromEntries(new URL(url).searchParams)
    return oauth2_token_id;
});
  
  console.log(results) // [ '57447761', '57447823', '57447915' ]

Since ids are all numeric, use a regular expression with a capturing group.

const rx = /_id=(\d+)/g
const m = rx.exec(url)
const ids=[]
while (m) {
 ids.push(m[1])
 m = rx.exec(url)
}

Use a Set if you need unique values. Use a Map and another capturing group if you need to capture the prefixed id name.

Or just parse the query string and get the values directly from the query map.

Related