1. unique()
PHPのarray_unique()。配列の中で重複した値を返します。Array.prototype.unique = function (sort, sortingFunction) { var array = []; for (var i = 0; i < this.length; i++) { if (array.inArray(this[i]) === false) array.push(this[i]); } if (sort === true) { if (typeof sortingFunction === 'function') array.sort(sortingFunction); else array.sort(); } return array; };
例
var array = [1, 2, 9, 6, 2, 1, 9, 3]; console.log(array.unique()); // print [1, 2, 9, 6, 3] console.log(array.unique(true)); // print [1, 2, 3, 6, 9]
2. htmlSpecialChars()
PHPのhtmlspecialchars()。特殊文字を HTMLエンティティに変換。String.prototype.htmlSpecialChars = function(){ return this .replace(/&/g, '&') .replace(/</g, '<') .replace(/>/g, '>') .replace(/"/g, '"'); };
例
var string = 'Me, myself & I like to "code" <html>'; console.log(string); // print Me, myself & I like to "code" <html> string = string.htmlSpecialChars(); console.log(string); // print Me, myself & I like to "code" <html>
3. htmlSpecialCharsDecode()
PHPのhtmlspecialchars_decode()。特殊な HTML エンティティを文字に戻します。String.prototype.htmlSpecialCharsDecode = function(){ return this .replace(/&/g, '&') .replace(/</g, '<') .replace(/>/g, '>') .replace(/"/g, '"'); };
例
var string = 'Me, myself & I like to "code" <html>'; console.log(string); // print Me, myself & I like to "code" <html> string = string.htmlSpecialChars(); console.log(string); // print Me, myself & I like to "code" <html> string = string.htmlSpecialCharsDecode(); console.log(string); // print Me, myself & I like to "code" <html>
4. ucwords()
PHPのucwords()。文字列の各単語の最初の文字を大文字にします。String.prototype.ucwords = function() { var words = this.split(/(\s+)/); for(var i = 0; i < words.length; i++) words[i] = words[i][0].toUpperCase() + words[i].substr(1, words[i].length); return words.join(''); };
例
var string = 'my name is aurelio de rosa'; console.log(string.ucwords()); // print My Name Is Aurelio De Rosa
5. ucfirst()
PHPのucfirst()。文字列の最初の文字を大文字にします。String.prototype.ucfirst = function() { var words = this.split(/(\s+)/); if (words[0] != null) words[0] = words[0][0].toUpperCase() + words[0].substr(1, words[0].length); return words.join(''); };
例
var string = 'my name is aurelio de rosa'; console.log(string.ucfirst()); // print My name is aurelio de rosa
後記
JavaScriptでもjQueryやUnderscore.jsなどのライブラリを使うことが前提のケースがほとんどなので上記のような実装をすることは無いとは思いますが、他言語の便利な関数を移植するために考えることは、よい勉強になりました。
0 件のコメント:
コメントを投稿