私自身の提案は次のとおりです。
$(".ordinal").text(function (i, t) {
i++;
var str = i.toString().slice(-1),
ord = '';
switch (str) {
case '1':
ord = 'st';
break;
case '2':
ord = 'nd';
break;
case '3':
ord = 'rd';
break;
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '0':
ord = 'th';
break;
}
return i + ord;
});
JS フィドルのデモ。
これは事実上、インクリメントされた数値 ( noti++
から開始するために) を取得し、それを文字列に変換してから、その文字列の最後の番号を調べます。序数は純粋にその最後の数値に基づいているため、これは任意の数値に対して機能するはずです。1
0
Number
プロトタイプを拡張して、この機能を実装することもできます。
Number.prototype.ordinate = function(){
var num = this + 1,
last = num.toString().slice(-1),
ord = '';
switch (last) {
case '1':
ord = 'st';
break;
case '2':
ord = 'nd';
break;
case '3':
ord = 'rd';
break;
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '0':
ord = 'th';
break;
}
return num.toString() + ord;
};
$(".ordinal").text(function (i, t) {
return i.ordinate();
});
JS フィドルのデモ。
わずかな代替手段を提供するために編集されました:
Number.prototype.ordinate = function(){
var num = this,
last = num.toString().slice(-1),
ord = '';
switch (last) {
case '1':
ord = 'st';
break;
case '2':
ord = 'nd';
break;
case '3':
ord = 'rd';
break;
default:
ord = 'th';
break;
}
return num.toString() + ord;
};
$(".ordinal").text(function (i,t) {
return t.replace(/(\d+)/g, function(a){
return parseInt(a, 10).ordinate();
});
});
JS フィドルのデモ。
これは基本的に各要素を繰り返し処理し.ordinal
、存在する数字を (同じ) 数字に置き換え、序数の接尾辞を追加します。
以下のコメントで提起された問題に対処するために編集され、 、、 、11
および12
(それぞれ)13
の序数接尾辞を受け取っていました。これは、すべての場合に修正されるようになりました。st
nd
rd
th
Number.prototype.ordinate = function(){
var num = this,
numStr = num.toString(),
last = numStr.slice(-1),
len = numStr.length,
ord = '';
switch (last) {
case '1':
ord = numStr.slice(-2) === '11' ? 'th' : 'st';
break;
case '2':
ord = numStr.slice(-2) === '12' ? 'th' : 'nd';
break;
case '3':
ord = numStr.slice(-2) === '13' ? 'th' : 'rd';
break;
default:
ord = 'th';
break;
}
return num.toString() + ord;
};
JS フィドルのデモ。
参考文献: