DIV CSS 佈局教程網

10 個值得收進口袋的原生 JavaScript 小技巧
編輯:關於JavaScript     

有些功能不難,但每次要寫都得重新查一遍。下面這十段常用的小工具函式,都是不依賴任何函式庫就能跑的原生寫法,適合直接放進自己的 utils 檔。

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

中文佔兩個字元、英文佔一個,直接 substring 會切壞。實務上的做法是逐字掃描並累加寬度。

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);
      if (patrn.exec(temp) == null) {
        icount = icount + 1;
      } else {
        icount = icount + 2;
      }
      strre += temp;
    } else {
      break;
    }
  }
  return strre + "...";
}

2. 取出網址中的主機名稱

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

今天更乾淨的寫法是 new URL(url).host,但正則版本在需要客製規則時仍很靈活。

3. 清除首尾空白

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

ES5 之後 String.prototype.trim() 已成為標準,這個實作現在主要是教學與相容舊環境的價值。

4. 全域取代

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

5. 轉義 HTML 標籤

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

6. 還原 HTML 標籤

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

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 或 toLocaleString(),省下自己拼字串的功夫。

8. 是否為純數字

function isDigit(value) {
  var patrn = /^[0-9]*$/;
  if (patrn.exec(value) == null || value == "") {
    return false;
  }
  return true;
}

9. 寫入 cookie

function setCookie(name, value, hours) {
  var d = new Date();
  var offset = 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 + "=" + escape(value) +
                    ";path=/;expires=" + exp.toGMTString() +
                    ";domain=example.com;";
}

10. 讀取 cookie

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

幾點提醒

這些片段堪用,但站在今天的角度有兩件事值得注意:一是盡量別直接擴充 Object.prototype 或內建物件原型,容易造成命名衝突;二是 cookie 的 escape() 已非推薦用法,改用 encodeURIComponent() 更安全。

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