DIV CSS 佈局教程網

JavaScript 字串與日期原型擴充方法大全
編輯:關於JavaScript     

把常用的小工具掛到 String.prototype、Number.prototype、Date.prototype 上,寫起來確實很像 C# 的擴充方法,程式碼也比較乾淨。以下整理一批實用範例,並在最後說明現代應該改用哪些替代方案。

基礎:去空格與合併空白

// 清除兩端的空格
String.prototype.trim = function () {
    return this.replace(/(^\s*)|(\s*$)/g, '');
};

// 把連續多個空白合併成一個
String.prototype.ResetBlank = function () {
    return this.replace(/\s+/g, ' ');
};

window.onload = function () {
    var str = "你  在  他想還好嗎?";
    alert(str.ResetBlank());     // "你 在 他想還好嗎?"
};

字串處理相關

// 只保留數字
String.prototype.GetNum = function () {
    return this.replace(/[^\d]/g, '');
};

// 只保留中文
String.prototype.GetCN = function () {
    return this.replace(/[^\u4e00-\u9fa5\uf900-\ufa2d]/g, '');
};

// 轉為 Number,轉不了就原字串回傳
String.prototype.ToInt = function () {
    return isNaN(parseInt(this)) ? this.toString() : parseInt(this);
};

// 取得位元組長度(中文算 2)
String.prototype.GetLen = function () {
    if (/^[\u4e00-\u9fa5\uf900-\ufa2d]+$/.test(this)) {
        return this.length * 2;
    }
    var oMatches = this.match(/[\x00-\xff]/g);
    return this.length * 2 - oMatches.length;
};

// 從路徑取檔名
String.prototype.GetFileName = function () {
    return this.replace(/^.*\/([^\/?]*).*$/, '$1');
};

// 從路徑取副檔名
String.prototype.GetExtensionName = function () {
    return this.replace(/^.*\/[^\/]*(\.[^\.?]*).*$/, '$1');
};

// 全域替換
String.prototype.replaceAll = function (reallyDo, replaceWith, ignoreCase) {
    if (!RegExp.prototype.isPrototypeOf(reallyDo)) {
        return this.replace(new RegExp(reallyDo, (ignoreCase ? "gi" : "g")), replaceWith);
    }
    return this.replace(reallyDo, replaceWith);
};

格式化與補零

// 類似 C# String.Format 的佔位符替換
String.Format = function () {
    if (arguments.length === 0) return '';
    if (arguments.length === 1) return arguments[0];
    var reg = /{(\d+)}/g;
    var args = arguments;
    return arguments[0].replace(reg, function ($0, $1) {
        return args[parseInt($1, 10) + 1];
    });
};

String.Format("Hello, {0}! You are {1}.", "World", 30);   // "Hello, World! You are 30."

// 數字左補零
Number.prototype.LenWithZero = function (oCount) {
    var strText = this.toString();
    while (strText.length < oCount) strText = '0' + strText;
    return strText;
};

(7).LenWithZero(3);        // "007"

// Unicode 還原為字元
Number.prototype.ChrW = function () {
    return String.fromCharCode(this);
};

// 日期格式化
Date.prototype.Format = function (format) {
    var o = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12,
        "H+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S":  this.getMilliseconds()
    };
    var week = ["日", "一", "二", "三", "四", "五", "六"];
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    if (/(E+)/.test(format)) {
        format = format.replace(RegExp.$1, ((RegExp.$1.length > 1)
            ? (RegExp.$1.length > 2 ? "星期" : "周") : "") + week[this.getDay()]);
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1,
                (RegExp.$1.length == 1) ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
};

new Date().Format("yyyy年MM月dd日 EEEE HH:mm:ss");

陣列操作

// 由小到大
Array.prototype.Min2Max = function () {
    var oValue;
    for (var i = 0; i < this.length; i++) {
        for (var j = 0; j <= i; j++) {
            if (this[i] < this[j]) { oValue = this[i]; this[i] = this[j]; this[j] = oValue; }
        }
    }
    return this;
};

// 由大到小
Array.prototype.Max2Min = function () {
    var oValue;
    for (var i = 0; i < this.length; i++) {
        for (var j = 0; j <= i; j++) {
            if (this[i] > this[j]) { oValue = this[i]; this[i] = this[j]; this[j] = oValue; }
        }
    }
    return this;
};

Array.prototype.GetMax = function () {
    var oValue = 0;
    for (var i = 0; i < this.length; i++) if (this[i] > oValue) oValue = this[i];
    return oValue;
};

Array.prototype.GetMin = function () {
    var oValue = 0;
    for (var i = 0; i < this.length; i++) if (this[i] < oValue) oValue = this[i];
    return oValue;
};

日期差計算與空值判斷

/** 計算兩個日期的差值 */
Date.prototype.Diff = function (interval, objDate) {
    if (arguments.length < 2 || objDate.constructor != Date) return undefined;
    switch (interval) {
        case 's': return parseInt((objDate - this) / 1000);            // 秒
        case 'n': return parseInt((objDate - this) / 60000);           // 分
        case 'h': return parseInt((objDate - this) / 3600000);         // 時
        case 'd': return parseInt((objDate - this) / 86400000);        // 日
        case 'w': return parseInt((objDate - this) / (86400000 * 7));  // 週
        case 'm': return (objDate.getMonth() + 1)
                        + ((objDate.getFullYear() - this.getFullYear()) * 12)
                        - (this.getMonth() + 1);                        // 月
        case 'y': return objDate.getFullYear() - this.getFullYear();   // 年
        default:  return undefined;
    }
};

/** 判斷是否為空(含 'NULL'、'UNDEFINED'、'{}' 等字串) */
Object.prototype.IsNullOrEmpty = function () {
    var obj = this;
    if (obj == null || obj == undefined || typeof obj == 'undefined' || obj == '') return true;
    if (typeof obj == 'string') {
        obj = obj.trim();
        if (obj == '') return true;
        obj = obj.toUpperCase();
        if (obj == 'NULL' || obj == 'UNDEFINED' || obj == '{}') return true;
    }
    return false;
};

為什麼現代不該再這樣寫

這些擴充在 jQuery 的年代很常見,但今天有幾個明確的問題值得說明。

污染全域原型。擴充 Object.prototype 尤其危險——它會讓 for...in 多列出屬性,並可能與第三方函式庫衝突。這是早年許多 bug 的根源。

覆蓋原生方法。原範例自行定義了 String.prototype.trim,但 ES5 已內建 trim()、trimStart()、trimEnd()。自行覆寫會造成行為不一致。

內建方案已完整覆蓋這些需求:

// 去空格
"  a  ".trim();

// 全域替換(ES2021)
"a-b-c".replaceAll("-", "+");

// 補零
String(7).padStart(3, "0");            // "007"

// 陣列排序(注意 toSorted 不改原陣列)
[3, 1, 2].sort(function (a, b) { return a - b; });

// 最大最小值
Math.max.apply(null, [3, 1, 2]);
Math.min(...[3, 1, 2]);

// 日期格式化
new Intl.DateTimeFormat('zh-TW', {
    year: 'numeric', month: 'long', day: 'numeric', weekday: 'long'
}).format(new Date());

// 空值判斷
value == null;            // 同時涵蓋 null 與 undefined
```

若確實需要擴充,比較恰當的做法有兩個:一是用 ES 模組導出獨立函式(export function trim(s) {...}),保持純函式、不污染原型;二是若真要掛原型,至少用 Object.defineProperty 並設 enumerable: false,避免干擾 for...in。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved