拡張メソッドをネイティブString型に追加したい。Ionic2カスタム拡張メソッドを追加する
文字列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();
}
使用法:
public slug: string = "UTF String".toSlug();
VSコードの提案は問題なく正常に動作します。しかしionic serve
後に、それは私のCLIのバージョンを以下に示しString.toSlug is not a function
をスロー:
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
任意の助けが理解されるであろう。ありがとう
インポートして使用するコードを共有できますか? –
Ionic build/srcディレクトリの* .tsファイルを自動インポートします。私はこの行を 'tsconfig.js':' 'include ':{ " src/**/*。ts " }' – trinvh
http://stackoverflow.com/questions/39877156/how-to-extend- string-prototype-and-it-next-in-typescript –