在日常開發中,我們常常會寫到一些重複性的 JS 處理程式碼。本文整理了几個相當實用的方法,包括取得 GET 請求參數、去除字串空格,以及時間格式化輸出。
function getPara(para){
if(location.href.indexOf("?") == -1){
// 沒有參數,則直接返回
return null;
} else{
// 取得 GET 請求 ? 號後面的字串
var urlQuery = location.href.split("?");
if(urlQuery[1].indexOf("&") == -1){ //只有一個參數
if (urlQuery[1].indexOf("=") == -1) {
//沒有等號,代表沒有參數
return null;
}else{
var keyValue = urlQuery[1].split("=");
var key = keyValue[0];
var value = keyValue[1];
if(key == para){
return value;
}
}
}else{
// 解析多個參數
var urlTerms = urlQuery[1].split("&");
for (var i = 0; i < urlTerms.length; i++) {
var keyValue = urlTerms[i].split("=");
var key = keyValue[0];
var value = keyValue[1];
if(key == para){
return value;
}
}
}
}
return null;
}
function leftTrim(str) {
if (str.charAt(0) == " ") {
str = str.slice(1);
str = leftTrim(str);
}
return str;
}
function rightTrim(str) {
if (str.length - 1 >= 0 && str.charAt(str.length - 1) == " ") {
str = str.slice(0, str.length - 1);
str = rightTrim(str);
}
return str;
}
/**
* 將時間轉換成固定格式輸出
* new Date().toFormatString('yyyy-MM-dd HH:mm:ss');
* new Date().toFormatString('yyyy/MM/dd hh:mm:ss');
* 支援關鍵字(yyyy、MM、dd、HH、hh、mm、ss)
* HH 表示 24 小時制,hh 表示 12 小時制
*/
Date.prototype.toFormatString = function(format){
var formatstr = format;
if(format != null && format != ""){
if(formatstr.indexOf("yyyy") >= 0){
formatstr = formatstr.replace("yyyy", this.getFullYear());
}
if(formatstr.indexOf("MM") >= 0){
var month = this.getMonth() + 1;
if(month < 10){ month = "0" + month; }
formatstr = formatstr.replace("MM", month);
}
if(formatstr.indexOf("dd") >= 0){
var day = this.getDate();
if(day < 10){ day = "0" + day; }
formatstr = formatstr.replace("dd", day);
}
var hours = this.getHours();
if(formatstr.indexOf("HH") >= 0){
formatstr = formatstr.replace("HH", hours);
}
if(formatstr.indexOf("hh") >= 0){
if(hours > 12){ hours = hours - 12; }
if(hours < 10){ hours = "0" + hours; }
formatstr = formatstr.replace("hh", hours);
}
if(formatstr.indexOf("mm") >= 0){
var minute = this.getMinutes();
if(minute < 10){ minute = "0" + minute; }
formatstr = formatstr.replace("mm", minute);
}
if(formatstr.indexOf("ss") >= 0){
var second = this.getSeconds();
if(second < 10){ second = "0" + second; }
formatstr = formatstr.replace("ss", second);
}
}
return formatstr;
}
以上幾個小方法都是開發中經常會用到的,收藏起來能省下不少重複勞動。