Search code examples
javascripthtmlurlconsole

JavaScript get portion of a page URL


Is there a way using HTML css and JavaScript that I can find the URL of a webpage after the first 10 characters. For example, if the URL is random.com/abc the program would only get the /abc part of the URl and log it in the console. How can this be done?


Solution

  • Yes, you can get this done, using window.location.href.

    Example output:

    window.location.href: 'https://stackoverflow.com/questions/69409934/javascript-get-portion-of-a-page-url'
    

    You can split this string now, and get desired part:

    window.location.href.split('/')
    

    Output:

    0: "https:"
    1: ""
    2: "stackoverflow.com"
    3: "questions"
    4: "69409934"
    5: "javascript-get-portion-of-a-page-url"
    length: 6
    

    Now log this into console:

    console.log(window.location.href.split('/')[3])
    

    Your result:

    'questions'