日常開發中,有些功能幾乎每個專案都要寫一次:抓網址參數、金額加千分位、格式化小數、產生日期字串。與其每次重寫,不如攢成一份自己的工具箱。
用正則從 location.href 中擷取指定參數的值:
function getUrlPara(paraName){
var sUrl = location.href;
var sReg = "(?://?|&){1}" + paraName + "=([^&]*)" ;
var re = new RegExp(sReg, "gi");
re.exec(sUrl);
return RegExp.$1;
}
把使用者輸入的頁碼帶進網址,指派給 location.href 即可完成客戶端導向:
var pn = $("#gotopagenum").val();
location.href = "NewList.aspx?pagenum=" + pn;
把數字加上逗號分隔,同時補齊兩位小數:
function Convert(money){
var s = money + "";
if (s.indexOf(".") == -1) s += ".00";
if (/\.\d$/.test(s)) s += "0";
while (/\d{4}(\.|,)/.test(s)) s = s.replace(/(\d)(\d{3}(\.|,))/, "$1,$2");
return s;
}
先容忍使用者輸入的逗號,再交給 isNaN 判斷:
function IsNumeric(txt){
if (txt == "") return false;
if (txt.indexOf(",") > 0) txt = txt.replace(",", "");
return !isNaN(txt);
}
用 Math.round 處理進位,再用迴圈補零,確保 5 會顯示成 5.00:
function changeTwoDecimal_f(x){
var f_x = parseFloat(x);
if (isNaN(f_x)){ alert('parameter error'); return false; }
f_x = Math.round(f_x * 100) / 100;
var s_x = f_x.toString();
var pos_decimal = s_x.indexOf('.');
if (pos_decimal < 0){ pos_decimal = s_x.length; s_x += '.'; }
while (s_x.length <= pos_decimal + 2) s_x += '0';
return s_x;
}
另外,若要單純做數值轉換,parseFloat 與 parseInt 是最直接的選擇;前者會保留小數,後者只取整數部分。
常用於查詢條件的預設值,例如起始日設為本月一日、結束日設為今天:
var now = new Date();
var year = now.getYear();
if (now.getYear() < 1900) year = now.getYear() + 1900;
var month = now.getMonth() + 1;
var day = now.getDate();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
$("#txtDate1").val(year + "-" + month + "-01");
$("#txtDate2").val(year + "-" + month + "-" + day);
這裡有個歷史包袱要留意:早期瀏覽器的 getYear() 會回傳四位數年份,因此才需要那段 < 1900 的補償判斷。現代專案建議直接用 getFullYear(),可以省下這三行。
某些情境下需要一個近似唯一的值,又不方便用 GUID,把年月日時分秒加上毫秒串接起來就是個實用的方案:
function NowTimeCode(){
var now = new Date();
var year = now.getYear();
if (now.getYear() < 1900) year = now.getYear() + 1900;
var month = now.getMonth() + 1, day = now.getDate();
var hour = now.getHours(), minutes = now.getMinutes();
var second = now.getSeconds(), millisecond = now.getMilliseconds();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
if (hour < 10) hour = "0" + hour;
if (minutes < 10) minutes = "0" + minutes;
if (second < 10) second = "0" + second;
if (millisecond < 10) millisecond = "00" + millisecond;
else if (millisecond < 100) millisecond = "0" + millisecond;
return year.toString() + month + day + hour + minutes + second + millisecond.toString();
}
毫秒一定要補到三位,否則同一秒內產生的編號長度不一,排序時會亂掉。若對唯一性要求高,還是在尾端加上隨機碼或改用 performance.now() 較保險。