Url parts helper for GET params (or fragment params) manipulation.
npm install @enterwell/url-helperEnterwell's UrlHelper is used for manipulating url GET params (or fragment params - like GET but only in fragment part of url - after '#' sign).
yarn add @enterwell/url-helper
`
or with npm
`
npm install @enterwell/url-helper
`
Usage
Import UrlHelper just as any npm package:
`javascript
import UrlHelper from '@enterwell/url-helper';
`
Configuration
Constructor of the UrlHelper class receives two bool parameters - useFragment and useStrict.
useFragment - Flag used to mark that url fragment is used to store params. Default value is false so GET params are used by default.
useStrict - Flag used to instantiate url helper in strict mode (or not). When it is in strict mode all non-json values (params that have values that cannot be parsed using JSON.decode) are not loaded. If not in strict mode those valued are assumed to be strings and loaded that way.
Example:
`javascript
// Init url helper to work with GET url params.
const urlGetParamsHelper = new UrlHelper();
// Init url helper to work with fragment params (after '#' sign)
const urlFragmentParamsHelper = new UrlHelper(true);
`
API methods
$3
This method returns object with all url params found on current page (page URL). Object keys are param variable names and object values are param values.
If there is no URL params this method returns empt object.
$3
Method returns single param value. Param name to get value for is passed as argument and param value is returned from this method.
$3
Method is used to add (or update) param value for param identified by param name. Param value is serialized using JSON.stringify and encoded using uriEncode.
Code usage
Few examples of using this helper:
`javascript
// Let's say current url is https://enterwell.space
import UrlHelper from '@enterwell/url-helper';
// Init url helper with GET params
const urlHelper = new UrlHelper();
// Get url params
console.log(urlHelper.getUrlParams()) // Outputs {} since there is no url params
// Add foo param with bar value
urlHelper.addOrUpdateParam('foo', 'bar');
// URL is now: https://enterwell.space?foo=bar
// Add new param
urlHelper.addOrUpdateParam('obj', { foo: 'bar '});
// URL: https://enterwell.space?foo=bar&obj=%7B%22foo%22:%22bar%20%22%7D
// Update existing param
urlHelper.addOrUpdateParam('obj', 3);
// URL: https://enterwell.space?foo=bar&obj=3
// Show all params
console.log(urlHelper.getUrlParams()); // Outputs { foo: 'bar', obj: '3' }
// Unset param
urlHelper.addOrUpdateParam('foo', '');
// URL: https://enterwell.space?obj=3
``