Angular2 – writing custom utility class
May 27, 2016
If you are building an enterprise app, you may require to add custom utility classes.
Below is an example of a custom utility class CustomUtils that has a single method to get the query parameter from a url string.
export class CustomUtils {
public static noop() {
// skip
}
public static param(name:string, url:string):string {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
}
Usage
let url = 'ftp://google.com/?x=y&z=a&id=1001&ll=11';
let id = CustomUtils.param('id',url); // id = 1001
