Getting out a product ID from URL - JavaScript

Viewed 23

I'm trying to catch only a product ID from a URL. The ID is broke into 2 pieces: https://www.example.org/category/first_part_of_ID-some_text-second_part_of_id

I was stuck with this function

  var ft = "ft_";
  var pod = "_";
  var pageUrl = window.location.href;
  var pageUrl1 = pageUrl.split("-")[1];
  var pageUrl2 = pageUrl.replace("/","");
return pageUrl2;
}

Can anyone please help me clearing out everything except for the numbers? I tried with 2 different functions and putting it together, but it also didn't work.

1 Answers

This answer assumes the id you are trying to extract will always follow /category/ in the URL as well as that the first and second parts of the id always be located between the -some_text- part of the url

const url = window.location.href;
const urlAfterCategory = url.split('/')[4];
const id = `${urlAfterCategory.split('-')[0]}${urlAfterCategory.split('-')[2]}`
console.log(id); // Your id
Related