3

I want to add extension method to native String type.

string-extension.ts:

interface String {
    toSlug(): string;
}

String.prototype.toSlug = function () {
    var str = this.toLowerCase();
    str = str.replace(/à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ  |ặ|ẳ|ẵ/g, "a");
    str = str.replace(/è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ/g, "e");
    str = str.replace(/ì|í|ị|ỉ|ĩ/g, "i");
    str = str.replace(/ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ  |ợ|ở|ỡ/g, "o");
    str = str.replace(/ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ/g, "u");
    str = str.replace(/ỳ|ý|ỵ|ỷ|ỹ/g, "y");
    str = str.replace(/đ/g, "d");
    str = str.replace(/!|@|%|\^|\*|\(|\)|\+|\=|\<|\>|\?|\/|,|\.|\:|\;|\'| |\"|\&|\#|\[|\]|~|$|_/g, " ");
    str = str.replace(/-+-/g, " ");
    str = str.replace(/^\-+|\-+$/g, "");
    return str.trim();
}

Usage:

public slug: string = "UTF String".toSlug();

VS Code suggestion works fine without any problem. However after ionic serve it throws String.toSlug is not a function

Following is my CLI version:

Cordova CLI: 6.4.0 Ionic Framework Version: 2.0.0-rc.3 Ionic CLI Version: 2.1.13 Ionic App Lib Version: 2.1.7 Ionic App Scripts Version: 0.0.45 ios-deploy version: Not installed ios-sim version: Not installed OS: Windows 10 Node Version: v6.9.1

Any help will be appreciated. Thanks

trinvh
  • 1,500
  • 2
  • 11
  • 20

1 Answers1

1

I found the answer. Solution is import extension files into app.module.ts:

import '../extentions/string.ts';
import '../extensions/array.ts';
...

Change prototype into this (angular 2+):

String.prototype.toSlug = function (this:string) { ... }

Problem is ionic-app-script module does not include files while compiling.

trinvh
  • 1,500
  • 2
  • 11
  • 20