Search code examples
javascriptts-jest

Get the middle ID after the "com/ in the url string below in JavaScript


I would like to extract the middle ID from below string

const url = "https://state.velon.com/11eb35c9-3c69-e7f2-a4eb-0ac9483cdf87/reports/corporate";

And I want to grab the middle ID = "11eb35c9-3c69-e7f2-a4eb-0ac9483cdf87" from the string

Should I just use substring and index of or are there other ways of doing that. Please help


Solution

  • Using the built-in URL api is probably the canonical way and the safest way to do it:

    const urlString = "https://state.velon.com/11eb35c9-3c69-e7f2-a4eb-0ac9483cdf87/reports/corporate";
    
    const url = new URL(urlString);
    
    console.log(url.pathname.split("/")[1]);

    URLs can get pretty crazy, so we should just rely on the built-in way to parse it for us :)