URL
An object for creating, reading, and changing URLs. It breaks an address into parts: protocol, host, path, and parameters.
- Returns
- A new
URLobject. For an invalid address the constructor throws aTypeError.
Example
#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)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
#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 supplybase.base
optional, string or URL
The base address the relative address is resolved against.
More examples
#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'))The space in the value turned into + in the address. searchParams.get() returns the value back in its normal form.
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)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.
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'))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 aTypeErrorfor an invalid address. You can also check it beforehand withURL.canParse(). - Turn the current page’s address into an object with
new URL(location.href), and back into a string withurl.hreforString(url).
Related entries
#- URLSearchParamsAn object for reading and building query parameters in an address, the part after the ? character, e.g. ?course=js&page=2.
- locationAn object with information about the current page’s address. Lets you read its parts and navigate to a different address.
- history.pushState()Adds a new entry to the browser history and changes the address bar without reloading the page.
- fetch()Sends an HTTP request and returns a promise with the server’s response (a Response object).
- try...catchCatches errors thrown in the try block and handles them in catch. The optional finally always runs.
Spotted a mistake or missing an example? Write to us.