Last active
August 29, 2015 14:16
-
-
Save hrdaya/f088d29c85c8e95b05b4 to your computer and use it in GitHub Desktop.
文字列を数字に変換する(全角は半角に変換・数字以外の文字列は削除) ref: http://qiita.com/hrdaya/items/7c41b38c8aef96a4facf
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 文字列を整数にして返す | |
* | |
* @param {String} val 変換する文字列 | |
* @return {integer} parseIntで10進数に変換した数値 | |
* 整数に変換できない場合は0を返す | |
* 最初に全角の数字、ドット、ハイフン、マイナスは半角に変換 | |
*/ | |
var toInteger = function (val) { | |
// 保険でtoStringしておく | |
val = val.toString(); | |
// 全角を半角に変換(ハイフン、ドット、数字以外を取り除く) | |
var num = val.replace(/[0-9.‐-]/g, function (s) { | |
return String.fromCharCode(s.charCodeAt(0) - 65248); | |
}).replace(/(?!^\-)[^\d\.]/g, ""); | |
// 整数に変換 | |
num = parseInt(num, 10); | |
// 整数にパース出来なかったときは0を返す | |
return isNaN(num) ? 0 : num; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 文字列を整数にして返す | |
* | |
* @return {integer} parseIntで10進数に変換した数値 | |
* 整数に変換できない場合は0を返す | |
* 最初に全角の数字、ドット、ハイフン、マイナスは半角に変換 | |
*/ | |
String.prototype.toInteger = function () { | |
// 全角を半角に変換(ハイフン、ドット、数字以外を取り除く) | |
var num = this.replace(/[0-9.‐-]/g, function (s) { | |
return String.fromCharCode(s.charCodeAt(0) - 65248); | |
}).replace(/(?!^\-)[^\d\.]/g, ""); | |
// 整数に変換 | |
num = parseInt(num, 10); | |
// 整数にパース出来なかったときは0を返す | |
return isNaN(num) ? 0 : num; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment