Skip to main content

URL

The @wordpress/url package provides a comprehensive collection of utilities for manipulating URLs in JavaScript. It includes functions for working with query strings, validating URL components, and parsing URL parts.

Installation

You can install the package using npm:
npm install @wordpress/url --save
This package assumes your code will run in an ES2015+ environment. If you’re targeting environments with limited support for modern JavaScript features, include the polyfill from @wordpress/babel-preset-default.

Query String Utilities

addQueryArgs( url, args )

Appends arguments as querystring to the provided URL. If the URL already includes query arguments, the arguments are merged with (and take precedent over) the existing set.
url
string
required
URL to which arguments should be appended. If omitted, only the resulting querystring is returned.
args
object
required
Query arguments to apply to URL.
return
string
URL with arguments applied.
import { addQueryArgs } from '@wordpress/url';

const newURL = addQueryArgs( 'https://google.com', { q: 'test' } );
// Result: "https://google.com/?q=test"

buildQueryString( data )

Generates URL-encoded query string using input query data. This function behaves equivalent to PHP’s http_build_query, configured with encoding type PHP_QUERY_RFC3986 (spaces as %20).
data
object
required
Data to encode.
return
string
Query string.
import { buildQueryString } from '@wordpress/url';

const queryString = buildQueryString( {
	simple: 'is ok',
	arrays: [ 'are', 'fine', 'too' ],
	objects: {
		evenNested: {
			ok: 'yes',
		},
	},
} );
// Result: "simple=is%20ok&arrays%5B0%5D=are&arrays%5B1%5D=fine&arrays%5B2%5D=too&objects%5BevenNested%5D%5Bok%5D=yes"

getQueryArg( url, arg )

Returns a single query argument of the URL.
url
string
required
URL to parse.
arg
string
required
Query arg name.
return
string | undefined
Query arg value.
import { getQueryArg } from '@wordpress/url';

const foo = getQueryArg( 'https://wordpress.org?foo=bar&bar=baz', 'foo' );
// Result: "bar"

getQueryArgs( url )

Returns an object of query arguments of the given URL. If the URL is invalid or has no querystring, an empty object is returned.
url
string
required
URL to parse.
return
object
Query args object.
import { getQueryArgs } from '@wordpress/url';

const args = getQueryArgs( 'https://wordpress.org?foo=bar&bar=baz' );
// Result: { "foo": "bar", "bar": "baz" }

getQueryString( url )

Returns the query string part of the URL.
url
string
required
The full URL.
return
string | void
The query string part of the URL.
import { getQueryString } from '@wordpress/url';

const queryString = getQueryString(
	'http://localhost:8080/this/is/a/test?query=true#fragment'
);
// Result: "query=true"

hasQueryArg( url, arg )

Determines whether the URL contains a given query arg.
url
string
required
URL to check.
arg
string
required
Query arg name.
return
boolean
Whether or not the URL contains the query arg.
import { hasQueryArg } from '@wordpress/url';

const hasBar = hasQueryArg( 'https://wordpress.org?foo=bar&bar=baz', 'bar' );
// Result: true

removeQueryArgs( url, …args )

Removes arguments from the query string of the URL.
url
string
required
URL to modify.
args
string[]
required
Query arg names to remove.
return
string
Updated URL.
import { removeQueryArgs } from '@wordpress/url';

const newUrl = removeQueryArgs(
	'https://wordpress.org?foo=bar&bar=baz&baz=foobar',
	'foo',
	'bar'
);
// Result: "https://wordpress.org?baz=foobar"

URL Parsing

getProtocol( url )

Returns the protocol part of the URL.
url
string
required
The full URL.
return
string | void
The protocol part of the URL.
import { getProtocol } from '@wordpress/url';

const protocol1 = getProtocol( 'tel:012345678' ); // "tel:"
const protocol2 = getProtocol( 'https://wordpress.org' ); // "https:"

getAuthority( url )

Returns the authority part of the URL.
url
string
required
The full URL.
return
string | void
The authority part of the URL.
import { getAuthority } from '@wordpress/url';

const authority1 = getAuthority( 'https://wordpress.org/help/' ); // "wordpress.org"
const authority2 = getAuthority( 'https://localhost:8080/test/' ); // "localhost:8080"

getPath( url )

Returns the path part of the URL.
url
string
required
The full URL.
return
string | void
The path part of the URL.
import { getPath } from '@wordpress/url';

const path1 = getPath( 'http://localhost:8080/this/is/a/test?query=true' ); // "this/is/a/test"
const path2 = getPath( 'https://wordpress.org/help/faq/' ); // "help/faq"

getPathAndQueryString( url )

Returns the path part and query string part of the URL.
url
string
required
The full URL.
return
string
The path part and query string part of the URL.
import { getPathAndQueryString } from '@wordpress/url';

const pathAndQuery = getPathAndQueryString(
	'http://localhost:8080/this/is/a/test?query=true'
);
// Result: "/this/is/a/test?query=true"

getFragment( url )

Returns the fragment part of the URL.
url
string
required
The full URL.
return
string | void
The fragment part of the URL.
import { getFragment } from '@wordpress/url';

const fragment = getFragment(
	'http://localhost:8080/this/is/a/test?query=true#fragment'
);
// Result: "#fragment"

getFilename( url )

Returns the filename part of the URL.
url
string
required
The full URL.
return
string | void
The filename part of the URL.
import { getFilename } from '@wordpress/url';

const filename1 = getFilename( 'http://localhost:8080/this/is/a/test.jpg' ); // "test.jpg"
const filename2 = getFilename( '/this/is/a/test.png' ); // "test.png"

URL Validation

isURL( url )

Determines whether the given string looks like a URL.
url
string
required
The string to scrutinise.
return
boolean
Whether or not it looks like a URL.
import { isURL } from '@wordpress/url';

const result = isURL( 'https://wordpress.org' ); // true

isEmail( email )

Determines whether the given string looks like an email.
email
string
required
The string to scrutinise.
return
boolean
Whether or not it looks like an email.
import { isEmail } from '@wordpress/url';

const result = isEmail( '[email protected]' ); // true

isPhoneNumber( phoneNumber )

Determines whether the given string looks like a phone number.
phoneNumber
string
required
The string to scrutinize.
return
boolean
Whether or not it looks like a phone number.
import { isPhoneNumber } from '@wordpress/url';

const result = isPhoneNumber( '+1 (555) 123-4567' ); // true

isValidProtocol( protocol )

Tests if a URL protocol is valid.
protocol
string
required
The URL protocol.
return
boolean
True if the argument is a valid protocol (e.g. http:, tel:).
import { isValidProtocol } from '@wordpress/url';

const isValid = isValidProtocol( 'https:' ); // true
const isNotValid = isValidProtocol( 'https :' ); // false

isValidAuthority( authority )

Checks for invalid characters within the provided authority.
authority
string
required
A string containing the URL authority.
return
boolean
True if the argument contains a valid authority.
import { isValidAuthority } from '@wordpress/url';

const isValid = isValidAuthority( 'wordpress.org' ); // true
const isNotValid = isValidAuthority( 'wordpress#org' ); // false

isValidPath( path )

Checks for invalid characters within the provided path.
path
string
required
The URL path.
return
boolean
True if the argument contains a valid path.
import { isValidPath } from '@wordpress/url';

const isValid = isValidPath( 'test/path/' ); // true
const isNotValid = isValidPath( '/invalid?test/path/' ); // false

isValidQueryString( queryString )

Checks for invalid characters within the provided query string.
queryString
string
required
The query string.
return
boolean
True if the argument contains a valid query string.
import { isValidQueryString } from '@wordpress/url';

const isValid = isValidQueryString( 'query=true&another=false' ); // true
const isNotValid = isValidQueryString( 'query=true?another=false' ); // false

isValidFragment( fragment )

Checks for invalid characters within the provided fragment.
fragment
string
required
The URL fragment.
return
boolean
True if the argument contains a valid fragment.
import { isValidFragment } from '@wordpress/url';

const isValid = isValidFragment( '#valid-fragment' ); // true
const isNotValid = isValidFragment( '#invalid-#fragment' ); // false

URL Manipulation

prependHTTP( url )

Prepends “http://” to a URL, if it looks like something that is meant to be a TLD.
url
string
required
The URL to test.
return
string
The updated URL.
import { prependHTTP } from '@wordpress/url';

const actualURL = prependHTTP( 'wordpress.org' );
// Result: "http://wordpress.org"

prependHTTPS( url )

Prepends “https://” to a URL, if it looks like something that is meant to be a TLD.
url
string
required
The URL to test.
return
string
The updated URL.
This function will not replace “http://” with “https://“.
import { prependHTTPS } from '@wordpress/url';

const actualURL = prependHTTPS( 'wordpress.org' );
// Result: "https://wordpress.org"

filterURLForDisplay( url, maxLength )

Returns a URL for display purposes.
url
string
required
Original URL.
maxLength
number | null
URL length limit.
return
string
Displayed URL.
import { filterURLForDisplay } from '@wordpress/url';

const displayUrl = filterURLForDisplay(
	'https://www.wordpress.org/gutenberg/'
);
// Result: "wordpress.org/gutenberg"

const imageUrl = filterURLForDisplay(
	'https://www.wordpress.org/wp-content/uploads/img.png',
	20
);
// Result: "…ent/uploads/img.png"

cleanForSlug( string )

Performs basic cleanup of a string for use as a post slug. This approximates what sanitize_title_with_dashes() does in WordPress core.
string
string
required
Title or slug to be processed.
return
string
Processed string.
import { cleanForSlug } from '@wordpress/url';

const slug = cleanForSlug( 'Hello World!' );
// Result: "hello-world"
This function converts Latin-1 Supplement and Latin Extended-A letters to basic Latin letters, removes combining diacritical marks, converts whitespace/periods/slashes to hyphens, removes non-word characters except hyphens, and converts to lowercase.

normalizePath( path )

Returns a normalized path where equal query parameter values will be treated as identical, regardless of order.
path
string
required
Original path.
return
string
Normalized path.

Safe Decoding

safeDecodeURI( uri )

Safely decodes a URI with decodeURI. Returns the URI unmodified if decodeURI throws an error.
uri
string
required
URI to decode.
return
string
Decoded URI if possible.
import { safeDecodeURI } from '@wordpress/url';

const badUri = safeDecodeURI( '%z' );
// Result: "%z" (does not throw an Error)

safeDecodeURIComponent( uriComponent )

Safely decodes a URI component with decodeURIComponent. Returns the URI component unmodified if decodeURIComponent throws an error.
uriComponent
string
required
URI component to decode.
return
string
Decoded URI component if possible.

Complete Example

import { addQueryArgs, getQueryArgs, removeQueryArgs } from '@wordpress/url';

// Add query parameters
let url = addQueryArgs( 'https://example.com', {
	page: 2,
	filter: 'active'
} );
// Result: "https://example.com?page=2&filter=active"

// Get query parameters
const params = getQueryArgs( url );
// Result: { page: "2", filter: "active" }

// Remove query parameters
url = removeQueryArgs( url, 'filter' );
// Result: "https://example.com?page=2"

Version

Current version: 4.40.0

Build docs developers (and LLMs) love