DIV CSS 佈局教程網

10 個值得收藏的原生 JavaScript 實用小技巧
編輯:JavaScript綜合知識     

以下十個片段都是實戰中反覆用到的原生 JavaScript 工具函式,不需要引入任何外掛。直接收藏起來,需要的時候複製貼上即可。

1. 按「視覺寬度」截斷字串

中文佔兩個字元寬、英文佔一個,直接 substr 會把字切成一半。下面的做法用正則判斷是否為全形字元來累加寬度:

function cutstr(str, len) {
  var temp, icount = 0, strre = "";
  var patrn = /[^\x00-\xff]/;   // 非 ASCII 視為全形

  for (var i = 0; i < str.length; i++) {
    if (icount < len - 1) {
      temp = str.substr(i, 1);
      icount = patrn.exec(temp) == null ? icount + 1 : icount + 2;
      strre += temp;
    } else {
      break;
    }
  }
  return strre + "...";
}

2. 取出 URL 的網域主機

function getHost(url) {
  var host = "null";
  if (typeof url == "undefined" || null == url) {
    url = window.location.href;
  }
  var match = url.match(/^w+:\/\/\/([^/]*).*/);
  return (match != null) ? match[1] : host;
}

3. 清除字串兩端空白

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

現代瀏覽器早已內建 String.prototype.trim,這段主要作為理解與舊環境相容之用。

4. 全域替換

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

5. HTML 轉義

把使用者輸入的內容安全地放進 HTML,避免標籤被當成結構解析:

function HtmlEncode(text) {
  return text.replace(/&/g, '&')
             .replace(/"/g, '"')
             .replace(/</g, '<')
             .replace(/>/g, '>');
}

6. HTML 還原

function HtmlDecode(text) {
  return text.replace(/</g, '<')
             .replace(/>/g, '>')
             .replace(/"/g, '"')
             .replace(/&/g, '&');
}

注意還原時 & 一定要放在最後處理,否則會把已經還原的實體再轉一次,造成錯誤。

7. 日期格式化

擴充 Date 原型,支援 yyyy/MM/dd/HH/mm/ss 與星期:

Date.prototype.Format = function(formatStr) {
  var str = formatStr;
  var Week = ['日', '一', '二', '三', '四', '五', '六'];

  str = str.replace(/yyyy|YYYY/, this.getFullYear());
  str = str.replace(/MM/, this.getMonth() + 1 > 9 ? (this.getMonth() + 1) : '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() : '0' + this.getDate());
  str = str.replace(/d|D/g, this.getDate());
  str = str.replace(/hh|HH/, this.getHours() > 9 ? this.getHours() : '0' + this.getHours());
  str = str.replace(/h|H/g, this.getHours());
  str = str.replace(/mm/, this.getMinutes() > 9 ? this.getMinutes() : '0' + this.getMinutes());
  str = str.replace(/m/g, this.getMinutes());
  str = str.replace(/ss|SS/, this.getSeconds() > 9 ? this.getSeconds() : '0' + this.getSeconds());
  str = str.replace(/s|S/g, this.getSeconds());

  return str;
};

小提醒:這種「逐段 replace」的實作在遇到 yyyy-MM-dd 這類同時含大寫與小寫的格式時容易互相干擾,正式專案建議改用成熟方案或直接呼叫 toISOString() 再加工。

8. 判斷是否為純數字

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

9. 寫入 Cookie

function setCookie(name, value, Hours) {
  var d = new Date();
  var offset = 8;                                        // UTC+8
  var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
  var exp = new Date(utc + (3600000 * offset));
  exp.setTime(exp.getTime() + Hours * 60 * 60 * 1000);

  document.cookie = name + "=" + escape(value)
    + ";path=/;expires=" + exp.toUTCString()
    + ";domain=example.com;";
}

10. 讀取 Cookie

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

實際部署時請留意兩件事:escape/unescape 已不建議使用,改用 encodeURIComponent/decodeURIComponent;另外若 Cookie 涉及身分驗證,記得加上 Secure 與 HttpOnly 旗標,避免被第三方腳本讀取。

結語

這些片段共同的價值在於「零依賴、可讀性高、即拿即用」。理解背後的原理之後,多數情境你甚至不需要它們——現代 JavaScript 已經把 trim()、replaceAll()、Intl.DateTimeFormat 這些能力內建了。知道有這些工具存在,比背下實作更重要。

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