Angular2 – writing custom utility class

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

Add a Comment

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image