javascriptjquerypathname

How can I get pathname values from url in JavaScript?


I have this:

http://example.com/iu4pa9rm8vfh.html?param_1

I want this:

iu4pa9rm8vfh
var url ="http://example.com/iu4pa9rm8vfh.html?param_1";
  document.getElementById("demo").innerHTML = 
"The pathname of this page is :" + url.pathname;

Thanks in advance for any guidance!

update what is the problem in results

<!DOCTYPE html>
<html>

<body>

  <p id="demo"></p>

  <script>
    const url = new URL("http://example.com/iu4pa9rm8vfh.html?param_1")
    const pathname = url.pathname.match(/([0-9a-z]+)/)
    console.log(pathname[0])

    document.getElementById("demo").innerHTML = "The pathname of this page is :" + pathname;
  </script>

</body>

</html>


Solution

  • you can do it like this :

    const url = new URL('http://example.com/iu4pa9rm8vfh.html?param_1')
    let path = url.pathname.split('.')[0].replace('/','')
    document.getElementById("demo").innerHTML = "The pathname of this page is :" + path;
    

    <!DOCTYPE html>
    <html>
    
    <body>
    
      <p id="demo"></p>
    
      <script>
        const url = new URL('http://example.com/iu4pa9rm8vfh.html?param_1')
        let path = url.pathname.split('.')[0].replace('/','')
        document.getElementById("demo").innerHTML = "The pathname of this page is :" + path;
      </script>
    
    </body>
    
    </html>