url-composer
Small lib for parsing and building dynamic URLs
Install
You can install the lib via npm
npm install --save url-composer
or bower
bower install --save url-composer
Usage
The library is very simple to use
url// "https://github.com/RasCarlito?tab=repositories#your-repos-filter"
Everything is optional. So calling url.build()
without any parameters would just generate an empty String
.
Note: Path and query parameters are encoded using encodeURIComponent
Path options
The path option has an advanced syntax to handle injection of parameters.
Named parameters
Like in the first example
url// "/users/42"
Optional parameters
With optional parameters you can make a portion of the path
optional using parentheses.
Depending on the params
passed that portion will be included or left out.
const path = '/users/:id(/edit/:section)' url// "/users/42" url// "/users/42/edit/profile"
Testing a path
You can test a path to validate that it corresponds to a given schema
const path = '/users/:id(/edit/:section)' // Testing path directlyurl // trueurl // false // Getting the regex insteadconst re = url re // true
Parsing a path
You can parse a path to extract the dynamic parts into an Array
or an Object
.
It will also extract the search query if it is present and place it as the last item in the resulting Array
or in a query
key in the resulting Object
.
Missing optional parameters will result to null
in the extracted values.
Lets look at some code to actually see how it works:
// Parsing dynamic parts into an Arrayurl// ['42', 'profile', null] // Parsing dynamic parts into an Objecturl// { id: '42', section: 'profile', query: null } // Parsing a path with a search queryurl// ['42', 'profile', 'expand=true'] // Parsing dynamic parts into an Objecturl// { id: '42', section: 'profile', query: 'expand=true' }