NURL is a powerful URL manipulation library that extends the standard URL class. It provides dynamic segment processing and flexible URL creation capabilities.
import { NURL } from 'nurl'
// Create URL from string
const url1 = new NURL('https://example.com/users/123?name=John')
// Create URL from existing URL object
const standardUrl = new URL('https://example.com')
const url2 = new NURL(standardUrl)
// Create URL from custom options object
const url3 = new NURL({
baseUrl: 'https://example.com',
pathname: '/users/:id',
query: { id: '123', name: 'John' }
})
// Create empty URL
const url4 = new NURL()
// Using the factory function
const url5 = NURL.create('https://example.com')
// The factory function also works with options object
const url6 = NURL.create({
baseUrl: 'https://example.com',
pathname: '/users/:id',
query: { id: '123', name: 'John' }
})
NURL processes dynamic segments in the pathname and replaces them with values from the query object. If a dynamic segment doesn't have a corresponding query value, it remains unchanged in the pathname without any encoding:
const url = new NURL({
baseUrl: 'https://api.example.com',
pathname: '/users/:a/posts/[b]/[c]',
query: {
a: '123',
b: '456',
format: 'json'
}
})
console.log(url.href)
// Output: https://api.example.com/users/123/posts/456/[c]?format=json
NURL automatically handles Internationalized Domain Names:
const url = new NURL('https://한글.도메인')
console.log(url.hostname) // xn--bj0bj06e.xn--hq1bm8jm9l
console.log(url.decodedHostname) // 한글.도메인 (in human-readable format)
constructor(input?: string | URL | URLOptions)
input
: Can be one of the following:
string
: Standard URL stringURL
: Standard URL objectURLOptions
: Custom options object that extends Partial<URL>
and includes:baseUrl?: string
: Optional base URL stringquery?: Record<string, string>
: Optional object for query parameterspathname
, protocol
, etc.):paramName
or [paramName]
format in the pathname.NURL inherits all properties from the standard URL class:
href
, origin
, protocol
, username
, password
, host
, hostname
, port
, pathname
, search
, searchParams
, hash
toString()
: Returns the URL as a stringtoJSON()
: Returns the URL as a JSON representationURLOptions
, if a query value corresponding to a dynamic segment is missing, the dynamic segment remains unchanged in the pathname.:paramName
or [paramName]
format.