Skip to content

Instantly share code, notes, and snippets.

@s-hiroshi
Created April 12, 2013 01:25
Show Gist options
  • Save s-hiroshi/5368556 to your computer and use it in GitHub Desktop.
Save s-hiroshi/5368556 to your computer and use it in GitHub Desktop.
// 全角数字を半角数字に変換(toHalfNum)は下記のサイトのスクリプトを利用。
// http://ameblo.jp/pclindesk/entry-10110151969.html
function myError(str) {
$('#error').text(str);
}
$('#date').blur(function () {
var i;
var now = new Date();
var resultHtml = '';
var matches = [];
var year;
var month;
var dayOfWeek = ['日', '月', '火', '水', '木', '金', '土'];
// ヘルパー
// 全角数字を半角数字へ変換する(下記サイトのスクリプト)
// http://ameblo.jp/pclindesk/entry-10110151969.html
function toHalfNum(src) {
return src.replace(/[.0-9()]/g, function (wc) {
var zen = ".。0123456789()",
han = "..0123456789()";
return han[zen.indexOf(wc)];
});
};
// String.replaceのコールバック
function replaceHandler() {
// 空白を削除
arguments[0] = arguments[0].replace(/ /, '');
// 数字のみの場合は日を追加
if (arguments[0].match(/[^0-9]/) === null) {
// 月は0(1月)~11(12月) ※ 日は1~始まる
var year = now.getFullYear();
// getYearはブラウザによって挙動が異なる
var date = new Date(year, month, arguments[0]);
resultHtml += arguments[0] + '日(' + dayOfWeek[date.getDay()] + ')' + '\n';
} else {
resultHtml += arguments[0] + '' + '\n';
}
// 31(火)を31日(火)へ
resultHtml = resultHtml.replace(/([0-9]+)\(/g, '$1日(')
}
/*
* メイン処理開始
*/
// 年の処理
if ($('#year').val() !== '') {
year = parseInt($('#year').val(), 10);
} else {
year = now.getYear();
}
// 月の処理(月は0〜11)
if ($('#month').val() !== '') {
if (12 < parseInt($('#month').val(), 10)) {
myError('1〜12を入力');
return false;
}
month = parseInt($('#month').val(), 10) - 1;
} else {
month = now.getMonth();
}
// 改行による分割
var matches = $(this).val().split('\n');
// 行ごとの処理
for (i = 0; i < matches.length; i++) {
// 全角数字を半角数字へ
var match = toHalfNum(matches[i]);
// 区切文字(連続)を空白(1つ)へ統一
match = match.replace(/(\s|[,、])+/g, ' ');
// 空白で区切った文字列ごとの処理
resultHtml += '<' + (month + 1) + '月>' + '\n';
match.replace(/([^ ]+)( |$)?/g, replaceHandler);
resultHtml += '\n';
}
$('#result').text(resultHtml);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment