Security News
pnpm 10.0.0 Blocks Lifecycle Scripts by Default
pnpm 10 blocks lifecycle scripts by default to improve security, addressing supply chain attack risks but sparking debate over compatibility and workflow changes.
@wordpress/url
Advanced tools
@wordpress/url is a utility library for manipulating and parsing URLs in JavaScript. It provides a set of functions to handle URL strings, making it easier to work with URLs in web development, especially within the context of WordPress projects.
Parsing URLs
The parse function allows you to break down a URL into its components, such as protocol, hostname, pathname, and query string. This is useful for analyzing or modifying specific parts of a URL.
const { parse } = require('@wordpress/url');
const url = 'https://example.com/path?query=123';
const parsedUrl = parse(url);
console.log(parsedUrl);
Building URLs
The build function allows you to construct a URL from its components. This is useful when you need to dynamically generate URLs based on certain parameters.
const { build } = require('@wordpress/url');
const urlComponents = {
protocol: 'https',
hostname: 'example.com',
pathname: '/path',
query: { query: '123' }
};
const url = build(urlComponents);
console.log(url);
Modifying Query Parameters
The addQueryArgs function lets you add or modify query parameters in a URL. This is particularly useful for updating URLs with new query parameters without manually string manipulation.
const { addQueryArgs } = require('@wordpress/url');
const url = 'https://example.com/path';
const newUrl = addQueryArgs(url, { query: '123', another: '456' });
console.log(newUrl);
Removing Query Parameters
The removeQueryArgs function allows you to remove specific query parameters from a URL. This is helpful when you need to clean up URLs by removing unnecessary parameters.
const { removeQueryArgs } = require('@wordpress/url');
const url = 'https://example.com/path?query=123&another=456';
const newUrl = removeQueryArgs(url, 'query');
console.log(newUrl);
The 'url' package is a Node.js core module that provides utilities for URL resolution and parsing. It offers similar functionalities to @wordpress/url, such as parsing and formatting URLs. However, @wordpress/url is more focused on WordPress-specific use cases and provides additional utilities for query parameter manipulation.
The 'query-string' package is a popular library for parsing and stringifying URL query strings. It offers more advanced query string manipulation capabilities compared to @wordpress/url, but it does not handle the full URL parsing and building that @wordpress/url does.
The 'url-parse' package is a lightweight URL parser that works in both Node.js and the browser. It provides similar URL parsing and manipulation capabilities as @wordpress/url, but it is more general-purpose and not specifically tailored for WordPress development.
A collection of utilities to manipulate URLs.
Install the module
npm install @wordpress/url --save
This package assumes that your code will run in an ES2015+ environment. If you're using an environment that has limited or no support for such language features and APIs, you should include the polyfill shipped in @wordpress/babel-preset-default
in your code.
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.
Usage
const newURL = addQueryArgs( 'https://google.com', { q: 'test' } ); // https://google.com/?q=test
Parameters
[string]
: URL to which arguments should be appended. If omitted, only the resulting querystring is returned.[Object]
: Query arguments to apply to URL.Returns
string
: URL with arguments applied.Generates URL-encoded query string using input query data.
It is intended to behave equivalent as PHP's http_build_query
, configured with encoding type PHP_QUERY_RFC3986 (spaces as %20
).
Usage
const queryString = buildQueryString( {
simple: 'is ok',
arrays: [ 'are', 'fine', 'too' ],
objects: {
evenNested: {
ok: 'yes',
},
},
} );
// "simple=is%20ok&arrays%5B0%5D=are&arrays%5B1%5D=fine&arrays%5B2%5D=too&objects%5BevenNested%5D%5Bok%5D=yes"
Parameters
Record<string,*>
: Data to encode.Returns
string
: Query string.Performs some basic cleanup of a string for use as a post slug.
This replicates some of what sanitize_title()
does in WordPress core, but is only designed to approximate what the slug will be.
Converts Latin-1 Supplement and Latin Extended-A letters to basic Latin letters. Removes combining diacritical marks. Converts whitespace, periods, and forward slashes to hyphens. Removes any remaining non-word characters except hyphens. Converts remaining string to lowercase. It does not account for octets, HTML entities, or other encoded characters.
Parameters
string
: Title or slug to be processed.Returns
string
: Processed string.Returns a URL for display.
Usage
const displayUrl = filterURLForDisplay(
'https://www.wordpress.org/gutenberg/'
); // wordpress.org/gutenberg
const imageUrl = filterURLForDisplay(
'https://www.wordpress.org/wp-content/uploads/img.png',
20
); // …ent/uploads/img.png
Parameters
string
: Original URL.number|null
: URL length.Returns
string
: Displayed URL.Returns the authority part of the URL.
Usage
const authority1 = getAuthority( 'https://wordpress.org/help/' ); // 'wordpress.org'
const authority2 = getAuthority( 'https://localhost:8080/test/' ); // 'localhost:8080'
Parameters
string
: The full URL.Returns
string|void
: The authority part of the URL.Returns the filename part of the URL.
Usage
const filename1 = getFilename( 'http://localhost:8080/this/is/a/test.jpg' ); // 'test.jpg'
const filename2 = getFilename( '/this/is/a/test.png' ); // 'test.png'
Parameters
string
: The full URL.Returns
string|void
: The filename part of the URL.Returns the fragment part of the URL.
Usage
const fragment1 = getFragment(
'http://localhost:8080/this/is/a/test?query=true#fragment'
); // '#fragment'
const fragment2 = getFragment(
'https://wordpress.org#another-fragment?query=true'
); // '#another-fragment'
Parameters
string
: The full URLReturns
string|void
: The fragment part of the URL.Returns the path part of the URL.
Usage
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'
Parameters
string
: The full URL.Returns
string|void
: The path part of the URL.Returns the path part and query string part of the URL.
Usage
const pathAndQueryString1 = getPathAndQueryString(
'http://localhost:8080/this/is/a/test?query=true'
); // '/this/is/a/test?query=true'
const pathAndQueryString2 = getPathAndQueryString(
'https://wordpress.org/help/faq/'
); // '/help/faq'
Parameters
string
: The full URL.Returns
string
: The path part and query string part of the URL.Returns the protocol part of the URL.
Usage
const protocol1 = getProtocol( 'tel:012345678' ); // 'tel:'
const protocol2 = getProtocol( 'https://wordpress.org' ); // 'https:'
Parameters
string
: The full URL.Returns
string|void
: The protocol part of the URL.Returns a single query argument of the url
Usage
const foo = getQueryArg( 'https://wordpress.org?foo=bar&bar=baz', 'foo' ); // bar
Parameters
string
: URL.string
: Query arg name.Returns
QueryArgParsed|void
: Query arg value.Returns an object of query arguments of the given URL. If the given URL is invalid or has no querystring, an empty object is returned.
Usage
const foo = getQueryArgs( 'https://wordpress.org?foo=bar&bar=baz' );
// { "foo": "bar", "bar": "baz" }
Parameters
string
: URL.Returns
QueryArgs
: Query args object.Returns the query string part of the URL.
Usage
const queryString = getQueryString(
'http://localhost:8080/this/is/a/test?query=true#fragment'
); // 'query=true'
Parameters
string
: The full URL.Returns
string|void
: The query string part of the URL.Determines whether the URL contains a given query arg.
Usage
const hasBar = hasQueryArg( 'https://wordpress.org?foo=bar&bar=baz', 'bar' ); // true
Parameters
string
: URL.string
: Query arg name.Returns
boolean
: Whether or not the URL contains the query arg.Determines whether the given string looks like an email.
Usage
const isEmail = isEmail( 'hello@wordpress.org' ); // true
Parameters
string
: The string to scrutinise.Returns
boolean
: Whether or not it looks like an email.Determines whether the given string looks like a phone number.
Usage
const isPhoneNumber = isPhoneNumber( '+1 (555) 123-4567' ); // true
Parameters
string
: The string to scrutinize.Returns
boolean
: Whether or not it looks like a phone number.Determines whether the given string looks like a URL.
Related
Usage
const isURL = isURL( 'https://wordpress.org' ); // true
Parameters
string
: The string to scrutinise.Returns
boolean
: Whether or not it looks like a URL.Checks for invalid characters within the provided authority.
Usage
const isValid = isValidAuthority( 'wordpress.org' ); // true
const isNotValid = isValidAuthority( 'wordpress#org' ); // false
Parameters
string
: A string containing the URL authority.Returns
boolean
: True if the argument contains a valid authority.Checks for invalid characters within the provided fragment.
Usage
const isValid = isValidFragment( '#valid-fragment' ); // true
const isNotValid = isValidFragment( '#invalid-#fragment' ); // false
Parameters
string
: The url fragment.Returns
boolean
: True if the argument contains a valid fragment.Checks for invalid characters within the provided path.
Usage
const isValid = isValidPath( 'test/path/' ); // true
const isNotValid = isValidPath( '/invalid?test/path/' ); // false
Parameters
string
: The URL path.Returns
boolean
: True if the argument contains a valid pathTests if a url protocol is valid.
Usage
const isValid = isValidProtocol( 'https:' ); // true
const isNotValid = isValidProtocol( 'https :' ); // false
Parameters
string
: The url protocol.Returns
boolean
: True if the argument is a valid protocol (e.g. http:, tel:).Checks for invalid characters within the provided query string.
Usage
const isValid = isValidQueryString( 'query=true&another=false' ); // true
const isNotValid = isValidQueryString( 'query=true?another=false' ); // false
Parameters
string
: The query string.Returns
boolean
: True if the argument contains a valid query string.Given a path, returns a normalized path where equal query parameter values will be treated as identical, regardless of order they appear in the original text.
Parameters
string
: Original path.Returns
string
: Normalized path.Prepends "http://" to a url, if it looks like something that is meant to be a TLD.
Usage
const actualURL = prependHTTP( 'wordpress.org' ); // http://wordpress.org
Parameters
string
: The URL to test.Returns
string
: The updated URL.Prepends "https://" to a url, if it looks like something that is meant to be a TLD.
Note: this will not replace "http://" with "https://".
Usage
const actualURL = prependHTTPS( 'wordpress.org' ); // https://wordpress.org
Parameters
string
: The URL to test.Returns
string
: The updated URL.Removes arguments from the query string of the url
Usage
const newUrl = removeQueryArgs(
'https://wordpress.org?foo=bar&bar=baz&baz=foobar',
'foo',
'bar'
); // https://wordpress.org?baz=foobar
Parameters
string
: URL....string
: Query Args.Returns
string
: Updated URL.Safely decodes a URI with decodeURI
. Returns the URI unmodified if decodeURI
throws an error.
Usage
const badUri = safeDecodeURI( '%z' ); // does not throw an Error, simply returns '%z'
Parameters
string
: URI to decode.Returns
string
: Decoded URI if possible.Safely decodes a URI component with decodeURIComponent
. Returns the URI component unmodified if decodeURIComponent
throws an error.
Parameters
string
: URI component to decode.Returns
string
: Decoded URI component if possible.This is an individual package that's part of the Gutenberg project. The project is organized as a monorepo. It's made up of multiple self-contained software packages, each with a specific purpose. The packages in this monorepo are published to npm and used by WordPress as well as other software projects.
To find out more about contributing to this package or Gutenberg as a whole, please read the project's main contributor guide.
FAQs
WordPress URL utilities.
The npm package @wordpress/url receives a total of 119,082 weekly downloads. As such, @wordpress/url popularity was classified as popular.
We found that @wordpress/url demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
pnpm 10 blocks lifecycle scripts by default to improve security, addressing supply chain attack risks but sparking debate over compatibility and workflow changes.
Product
Socket now supports uv.lock files to ensure consistent, secure dependency resolution for Python projects and enhance supply chain security.
Research
Security News
Socket researchers have discovered multiple malicious npm packages targeting Solana private keys, abusing Gmail to exfiltrate the data and drain Solana wallets.