Skip to content

Instantly share code, notes, and snippets.

@sakahukamaki
Created May 8, 2018 13:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sakahukamaki/3c12ba97e86161a6d5044cb953a77cc9 to your computer and use it in GitHub Desktop.
Save sakahukamaki/3c12ba97e86161a6d5044cb953a77cc9 to your computer and use it in GitHub Desktop.
郵便番号を入力されたらもろもろ整形してハイフン含む形に成型する
// 全角数字を半角数字に変更
// -> 半角数字以外を除去
// -> xxx-xxxxの形に変更
function fixPostalCode(postal_code) {
const fixed = postal_code
.replace(/[0-9]/g, function(s) {
return String.fromCharCode(s.charCodeAt(0) - 65248);
})
.replace(/[^0-9]/g, '')
.replace(/^([0-9]{3})([0-9]{0,4}).*/, "$1-$2");
return fixed;
}
$(document).on('turbolinks:load', function() {
$("#input_postal_code").on("blur", function(){
let postal_code = $(this).val();
postal_code = fixPostalCode(postal_code);
$(this).val(postal_code);
});
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment