Skip to content

Instantly share code, notes, and snippets.

@iwbjp iwbjp/henkanObj.js Secret
Last active Feb 21, 2017

Embed
What would you like to do?
全角カナを半角カナに変換するJavaScriptツール(逆も可能)
function inverseObject(obj, keyIsNumber) {
return Object.keys(obj).reduceRight(function (ret, k) {
return (ret[obj[k]] = keyIsNumber ? parseInt(k, 10) : k, ret);
}, {});
}
var henkanObj = {
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': 'ソ',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': 'ガ',
'': 'ギ',
'': 'グ',
'': 'ゲ',
'': 'ゴ',
'': 'ザ',
'': 'ジ',
'': 'ズ',
'': 'ゼ',
'': 'ゾ',
'': 'ダ',
'': 'ヂ',
'': 'ヅ',
'': 'デ',
'': 'ド',
'': 'バ',
'': 'ビ',
'': 'ブ',
'': 'ベ',
'': 'ボ',
'': 'パ',
'': 'ピ',
'': 'プ',
'': 'ペ',
'': 'ポ',
'': 'ヴ',
'': 'ヷ',
'': 'ヺ',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': ''
};
var han2zen = function(str) {
var reg = new RegExp('(' + Object.keys(henkanObj).join('|') + ')', 'g');
return str.replace(reg, function(match) {
return henkanObj[match];
});
};
var zen2han = function(str) {
var k = inverseObject(henkanObj);
var reg = new RegExp('(' + Object.keys(k).join('|') + ')', 'g');
return str.replace(reg, function(match) {
return k[match];
});
};
var a = document.getElementById('a');
var b = document.getElementById('b');
var copy = document.getElementById('copy');
var notice = document.getElementById('notice');
var r = document.querySelector('[type="radio"]:first-child');
var rr = document.querySelectorAll('[type="radio"]');
a.addEventListener('input', function() {
b.value = r.checked ? han2zen(a.value) : zen2han(a.value);
});
copy.addEventListener('click', function() {
b.select();
document.execCommand('copy');
notice.textContent = 'コピーしました。';
setTimeout(function() {
notice.textContent = '';
}, 3000);
});
rr.forEach(function(i) {
i.addEventListener('click', function() {
b.value = r.checked ? han2zen(a.value) : zen2han(a.value);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.