Home » Featured, Headline, Software Development

Angular2 – writing custom utility class

27 May 2016 No Comment

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

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.

*
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