1.0.1 • Published 6 years ago

@enterwell/url-helper v1.0.1

Weekly downloads
-
License
MIT
Repository
-
Last release
6 years ago

Enterwell's UrlHelper is used for manipulating url GET params (or fragment params - like GET but only in fragment part of url - after '#' sign).

Installation

In order to install this package you have to be logged in to npm with enterwell account and then just execute command(s):

yarn add @enterwell/url-helper

or with npm

npm install @enterwell/url-helper

Usage

Import UrlHelper just as any npm package:

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:

// 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

getUrlParams(): object

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.

getParamValue( paramName: string ): any

Method returns single param value. Param name to get value for is passed as argument and param value is returned from this method.

addOrUpdateParam( paramName: string, paramValue: any )

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:

// 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
1.0.1

6 years ago

1.0.0

6 years ago