文字列に連鎖プロトタイプを使用したいと思います。しかし、私が返す文字列プロトタイプはもう適用されません。 this
を元の方法で返すことなく修正する方法。ネイティブString.prototype
と同じです。文字列に連鎖プロトタイプを使用する方法
function StringUtil(str){
this.str = str;
}
StringUtil.prototype.toCamelCase = function() {
return this.str.replace(/(?:^\w|[A-Z]|\b\w)/g, function(letter, index) {
return index === 0 ? letter.toLowerCase() : letter.toUpperCase();
}).replace(/\s+/g, '');
};
StringUtil.prototype.toSlug = function() {
return this.str.toString().toLowerCase()
.replace(/\s+/g, '-') // Replace spaces with -
.replace(/[^\w\-]+/g, '') // Remove all non-word chars
.replace(/\-\-+/g, '-') // Replace multiple - with single -
.replace(/^-+/, '') // Trim - from start of text
.replace(/-+$/, ''); // Trim - from end of text
};
var util = new StringUtil('this is a custom string');
console.log(util.toCamelCase()) // thisIsACustomString
console.log(util.toSlug()) // this-is-a-custom-string
util.toCamelCase().toSlug() // This does not work
すべてのメソッドで新しい 'StringUtil'オブジェクトを返すと、パフォーマンスに影響しますか? – user6571640
このケースでは何の問題もないと思います。とにかく@ gurvinder372の方法に従って、 'this'オブジェクトを返すことができます。 – ianaya89