JavaScriptBrowser APIs

URL

An object for creating, reading, and changing URLs. It breaks an address into parts: protocol, host, path, and parameters.

Returns
A new URL object. For an invalid address the constructor throws a TypeError.
On this page

Example

#
JavaScript
const address = 'https://codeworlds.com/courses/javascript?lesson=5&mode=study#exercises'
const url = new URL(address)

console.log(url.protocol)
console.log(url.hostname)
console.log(url.pathname)
console.log(url.search)
console.log(url.hash)
console.log(url.origin)
Console
https:
codeworlds.com
/courses/javascript
?lesson=5&mode=study
#exercises
https://codeworlds.com

Definition and usage

#

The new URL() constructor turns an address string into an object where each part of the address has its own property: protocol, hostname, port, pathname, search (the parameters after the ?), and hash (the fragment after the #), plus origin and the full address in href. Instead of slicing the string by hand, you read ready-made values.

You can also change the properties. After assigning a new path or fragment, the object builds a correct address itself and encodes special characters, such as spaces and accented letters. Query parameters are handled by the searchParams property, a URLSearchParams object with get(), set(), and append() methods.

The second argument is a base address. With it you can turn a relative path, such as "../courses", into a full address, exactly the way the browser does with links on a page. If the string isn’t a valid address, the constructor throws a TypeError. To check an address without handling exceptions, use URL.canParse().

Syntax

#
Syntax
new URL(url)
new URL(url, base)

url.href
url.origin
url.protocol
url.hostname
url.pathname
url.search
url.searchParams
url.hash

URL.canParse(url, base)

Parameters

#
  • url

    string

    The address to process. Can be relative if you supply base.
  • base

    optional, string or URL

    The base address the relative address is resolved against.

More examples

#
Changing part of the address
JavaScript
const address = 'https://codeworlds.com/courses'
const url = new URL(address)

url.pathname = '/courses/javascript'
url.searchParams.set('search', 'for loop')
url.hash = 'results'

console.log(url.href)
console.log(url.searchParams.get('search'))
Console
https://codeworlds.com/courses/javascript?search=for+loop#results
for loop

The space in the value turned into + in the address. searchParams.get() returns the value back in its normal form.

Relative address and base address
JavaScript
const base = 'https://codeworlds.com/courses/javascript/lesson-5'

console.log(new URL('lesson-6', base).href)
console.log(new URL('../python', base).href)
console.log(new URL('/ranking', base).href)
console.log(new URL('?page=2', base).href)
Console
https://codeworlds.com/courses/javascript/lesson-6
https://codeworlds.com/courses/python
https://codeworlds.com/ranking
https://codeworlds.com/courses/javascript/lesson-5?page=2

A relative address works just like the href attribute of a link on a page: lesson-6 replaces the last segment of the path, .. goes up one directory, and a leading slash starts from the site root.

Checking a link to a project
JavaScript
function isValidLink(text) {
  try {
    new URL(text)
    return true
  } catch {
    return false
  }
}

console.log(isValidLink('https://github.com/emma/calculator'))
console.log(isValidLink('github.com/emma/calculator'))
console.log(URL.canParse('mailto:contact@codeworlds.com'))
Console
true
false
true

An address without a protocol isn’t a valid absolute address, so the constructor throws. URL.canParse() gives the same result without a try...catch block.

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Don’t build addresses by concatenating strings. url.searchParams.set() and property assignments take care of encoding special characters for you.
  • Always handle the error for addresses coming from the user: new URL() throws a TypeError for an invalid address. You can also check it beforehand with URL.canParse().
  • Turn the current page’s address into an object with new URL(location.href), and back into a string with url.href or String(url).

Related entries

#

Spotted a mistake or missing an example? Write to us.