DIV CSS 佈局教程網

JavaScript 常用工具函式精選(上):字串、日期、Cookie 與事件綁定
編輯:關於JavaScript     

日常開發中有一些反覆出現的小需求:截斷字串、去空格、格式化日期、操作 Cookie、跨瀏覽器綁事件。本文收集了一批實用的工具函式,並標註現代寫法。

1. 字串長度截斷(中文算兩個字)

function cutstr(str, len) {
  var temp, icount = 0, patrn = /[^\x00-\xff]/, strre = "";
  for (var i = 0; i < str.length; i++) {
    if (icount < len - 1) {
      temp = str.substr(i, 1);
      if (patrn.exec(temp) == null) {
        icount = icount + 1;
      } else {
        icount = icount + 2;
      }
      strre += temp;
    } else {
      break;
    }
  }
  return strre + "...";
}

原理是用 /[^\x00-\xff]/ 判斷是否為非 ASCII 字元,中文算 2 個單位。現代寫法可以直接用 spread 轉陣列再 slice:

const cutstr = (s, n) => [...s].slice(0, n).join('') + '...';

2. 全域替換

String.prototype.replaceAll = function (s1, s2) {
  return this.replace(new RegExp(s1, "gm"), s2);
};

ES2021 已內建 replaceAll,不必自己擴充原型。注意擴充原生 prototype 容易造成衝突,能避免就避免。

3. 去除前後空格

String.prototype.trim = function () {
  return this.replace(/^\s*(.*?)\s*$/, "$1");
};

ES5 起 trim 已是標準方法,另有 trimStart / trimEnd 可只處理單側。

4. 只去左側或右側空格

function ltrim(s) { return s.replace(/^(\s*)/, ""); }
function rtrim(s) { return s.replace(/(\s*)$/, ""); }

或者直接用 s.trimStart() 與 s.trimEnd()。

5. 判斷是否以某字串開頭/結尾

String.prototype.startWith = function (s) { return this.indexOf(s) == 0; };
String.prototype.endWith = function (s) {
  var d = this.length - s.length;
  return (d >= 0 && this.lastIndexOf(s) == d);
};

標準做法是 s.startsWith(x) 與 s.endsWith(x),ES6 起可直接使用,且支援第二個參數指定起算位置。

6. 轉義 HTML 特殊字元

function HtmlEncode(text) {
  return text.replace(/&/g, '&amp;')
             .replace(/</g, '&lt;')
             .replace(/>/g, '&gt;')
             .replace(/"/g, '&quot;')
             .replace(/'/g, '&#39;');
}

這段程式碼非常重要:把使用者輸入直接插入 innerHTML 會造成 XSS。轉義順序必須先處理 &,否則後續插入的 &lt; 會被二次轉義。

更安全的做法是用 textContent 而非 innerHTML,瀏覽器會自動處理:

el.textContent = userInput;  // 天然安全

7. 日期格式化

Date.prototype.Format = function (formatStr) {
  var str = formatStr;
  var Week = ['日', '一', '二', '三', '四', '五', '六'];
  str = str.replace(/yyyy|YYYY/, this.getFullYear());
  str = str.replace(/yy|YY/, (this.getYear() % 100) > 9
        ? (this.getYear() % 100).toString() : '0' + (this.getYear() % 100));
  str = str.replace(/MM/, (this.getMonth() + 1) > 9
        ? (this.getMonth() + 1).toString() : '0' + (this.getMonth() + 1));
  str = str.replace(/M/g, this.getMonth() + 1);
  str = str.replace(/w|W/g, Week[this.getDay()]);
  str = str.replace(/dd|DD/, this.getDate() > 9
        ? this.getDate().toString() : '0' + this.getDate());
  str = str.replace(/d|D/g, this.getDate());
  str = str.replace(/hh|HH/, this.getHours() > 9
        ? this.getHours().toString() : '0' + this.getHours());
  str = str.replace(/h|H/g, this.getHours());
  str = str.replace(/mm/, this.getMinutes() > 9
        ? this.getMinutes().toString() : '0' + this.getMinutes());
  str = str.replace(/m/g, this.getMinutes());
  str = str.replace(/ss|SS/, this.getSeconds() > 9
        ? this.getSeconds().toString() : '0' + this.getSeconds());
  str = str.replace(/s|S/g, this.getSeconds());
  return str;
};

現代寫法用 Intl.DateTimeFormat,內建多語言與各地區格式:

new Intl.DateTimeFormat('zh-TW', {
  year: 'numeric', month: '2-digit', day: '2-digit',
  hour: '2-digit', minute: '2-digit'
}).format(new Date());
// 或用 toLocaleString('zh-TW') 取得預設格式

8. 判斷是否為純數字

function isDigit(value) {
  return /^[0-9]*$/.test(value) && value !== "";
}

若含小數或負號,改用 /^-?\d+(\.\d+)?$/,或直接用 Number.isFinite(Number(v))。

9. 設定 Cookie

function setCookie(name, value, hours) {
  var d = new Date();
  var offset = 8;  // UTC+8
  var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
  var nd = utc + (3600000 * offset);
  var exp = new Date(nd);
  exp.setTime(exp.getTime() + hours * 60 * 60 * 1000);
  document.cookie = name + "=" + encodeURIComponent(value)
    + ";path=/;expires=" + exp.toUTCString();
}

那幾行時區換算是多餘的,Date 物件本身就會以本地時區運作,直接寫 new Date(Date.now() + hours * 3600000) 即可。另外請用 encodeURIComponent 而非已被棄用的 escape。

10. 讀取 Cookie

function getCookie(name) {
  var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
  if (arr != null) return decodeURIComponent(arr[2]);
  return null;
}

11. 加入收藏/設為首頁

function AddFavorite(sURL, sTitle) {
  try {
    window.external.addFavorite(sURL, sTitle);
  } catch (e) {
    try {
      window.sidebar.addPanel(sTitle, sURL, "");
    } catch (e) {
      alert("加入收藏失敗,請使用 Ctrl+D 進行添加");
    }
  }
}

這類功能基於安全理由已被現代瀏覽器全面移除,程式碼保留僅供參考。設為首頁同理,已不可能實現。

12. 動態載入樣式檔

function LoadStyle(url) {
  try {
    document.createStyleSheet(url);   // 舊 IE
  } catch (e) {
    var cssLink = document.createElement('link');
    cssLink.rel = 'stylesheet';
    cssLink.type = 'text/css';
    cssLink.href = url;
    document.getElementsByTagName('head')[0].appendChild(cssLink);
  }
}

13. 跨瀏覽器綁定與移除事件

function addEventSamp(obj, evt, fn) {
  if (!obj) return;
  if (obj.addEventListener) {
    obj.addEventListener(evt, fn, false);
  } else if (obj.attachEvent) {
    obj.attachEvent('on' + evt, fn);
  } else {
    obj['on' + evt] = fn;
  }
}

移除事件的邏輯相同,只是把 addEventListener 換成 removeEventListener、attachEvent 換成 detachEvent。注意移除時傳入的函式參照必須與綁定時相同,否則移不掉——這也是為什麼不能用匿名函式做需要後續移除的監聽器。

如今只需支援現代瀏覽器時,直接用 el.addEventListener 即可,上面那層判斷都可以省下。

14. 依 ID 取元素

function $(id) {
  return !id ? null : document.getElementById(id);
}

現代寫法是 document.getElementById(id),或用 document.querySelector('#' + id) 統一用選擇器語法。

關於擴充 prototype

上面好幾個範例都直接在 String.prototype 上掛方法。這在早期很常見,但現在被視為不良實踐:一旦兩個函式庫擴充了同名方法,就會互相覆蓋,而且會讓 for...in 的行為變得難以預期。把工具函式放在獨立物件或模組中導出,是更安全的組織方式。

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