I have a URL "https://www.example.com/username" and I want to extract the username from the URL. For example 'https://www.facebook.com/david'
            Asked
            
        
        
            Active
            
        
            Viewed 3,665 times
        
    -2
            
            
        - 
                    Is the username always the path component of the url? – Andrew Eisenberg Apr 13 '19 at 03:07
- 
                    [`window.location.pathname`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/pathname) – Elan Hamburger Apr 13 '19 at 03:07
- 
                    how is `https://www.facebook.com/david` extracted from `https://www.example.com/username`? – Jaromanda X Apr 13 '19 at 03:09
- 
                    This should have been very easy to research enough yourself to at least come up with a starting point . [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) – charlietfl Apr 13 '19 at 03:24
- 
                    I just wan to get the parameter from the URLs stated above – Ifeora-emeka Apr 14 '19 at 01:24
3 Answers
2
             let href = "https://www.facebook.com/david"; 
// let href = "https://www.facebook.com/david"; // Current window url; 
// Creating URL object
let url = new URL(href);
console.log(url.pathname.substring(1));  // David
// If you looking for parameters after ? 
let exampleUrl = "https://www.facebook.com?name=david";
let paramUrl = new URL(exampleUrl);
console.log(paramUrl.searchParams.get("name"));   // david or null if not exist
 
    
    
        Mohamed Abdallah
        
- 796
- 6
- 20
0
            
            
        In node.js, you should use the url module.
const Url = require('url');
console.log(new Url('https://www.facebook.com/david').pathname);
// 'david'
 
    
    
        Andrew Eisenberg
        
- 28,387
- 9
- 92
- 148
0
            
            
        You can use URL API and if you want to get rid of leading / you can use substring after taking the pathname from url
let url = `https://www.example.com/username`
let url2 = `https://www.example.com/username/somevalue`
let parsed = (url)=> {
   let urlParsed = new URL(url)
   return urlParsed.pathname.substring(1)
}
console.log(parsed(url))
console.log(parsed(url2)) 
    
    
        Code Maniac
        
- 37,143
- 5
- 39
- 60
