[javascript] JavaScript - Get Portion of URL Path

What is the correct way to pull out just the path from a URL using JavaScript?

Example:
I have URL
http://www.somedomain.com/account/search?filter=a#top
but I would just like to get this portion
/account/search

I am using jQuery if there is anything there that can be leveraged.

This question is related to javascript jquery url

The answer is


There is a useful Web API method called URL

_x000D_
_x000D_
const url = new URL('http://www.somedomain.com/account/search?filter=a#top');_x000D_
console.log(url.pathname.split('/'));_x000D_
const params = new URLSearchParams(url.search)_x000D_
console.log(params.get("filter"))
_x000D_
_x000D_
_x000D_


In case you want to get parts of an URL that you have stored in a variable, I can recommend URL-Parse

const Url = require('url-parse');
const url = new Url('https://github.com/foo/bar');

According to the documentation, it extracts the following parts:

The returned url instance contains the following properties:

protocol: The protocol scheme of the URL (e.g. http:). slashes: A boolean which indicates whether the protocol is followed by two forward slashes (//). auth: Authentication information portion (e.g. username:password). username: Username of basic authentication. password: Password of basic authentication. host: Host name with port number. hostname: Host name without port number. port: Optional port number. pathname: URL path. query: Parsed object containing query string, unless parsing is set to false. hash: The "fragment" portion of the URL including the pound-sign (#). href: The full URL. origin: The origin of the URL.


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

Will give you an array containing all the URL parts, which you can access like a normal array.

Or an ever more elegant solution suggested by @Dylan, with only the path parts:

window.location.pathname.split('/');

If you have an abstract URL string (not from the current window.location), you can use this trick:

let yourUrlString = "http://example.com:3000/pathname/?search=test#hash";

let parser = document.createElement('a');
parser.href = yourUrlString;

parser.protocol; // => "http:"
parser.hostname; // => "example.com"
parser.port;     // => "3000"
parser.pathname; // => "/pathname/"
parser.search;   // => "?search=test"
parser.hash;     // => "#hash"
parser.host;     // => "example.com:3000"

Thanks to jlong


If this is the current url use window.location.pathname otherwise use this regular expression:

var reg = /.+?\:\/\/.+?(\/.+?)(?:#|\?|$)/;
var pathname = reg.exec( 'http://www.somedomain.com/account/search?filter=a#top' )[1];

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to url

What is the difference between URL parameters and query strings? Allow Access-Control-Allow-Origin header using HTML5 fetch API File URL "Not allowed to load local resource" in the Internet Browser Slack URL to open a channel from browser Getting absolute URLs using ASP.NET Core How do I load an HTTP URL with App Transport Security enabled in iOS 9? Adding form action in html in laravel React-router urls don't work when refreshing or writing manually URL for public Amazon S3 bucket How can I append a query parameter to an existing URL?