萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

100 個實用原生 JavaScript 工具函數精選(上):字符串、URL、Cookie、時間處理

純原生 JS 實現,零依賴、高性能、易樹搖。本文精選前 15 個高頻工具函數,涵蓋字符串截取、域名解析、空格清理、HTML 轉義、日期格式化、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);
      icount += patrn.test(temp) ? 2 : 1; // 中文算 2 字節
      strre += temp;
    } else break;
  }
  return strre + "...";
}

2. 從 URL 提取域名主機

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

3. 字符串去除首尾空格(polyfill)

String.prototype.trim = function() {
  return this.replace(/^\s+|\s+$/g, '');
};

4. 字符串全局替換

String.prototype.replaceAll = function(s1, s2) {
  return this.replace(new RegExp(s1.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gm'), s2);
};

5. HTML 實體編碼(防 XSS)

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

6. HTML 實體解碼

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

7. 日期格式化(擴展 Date 原型)

Date.prototype.Format = function(fmt) {
  var o = {
    "M+": this.getMonth() + 1,
    "d+": this.getDate(),
    "h+": this.getHours(),
    "m+": this.getMinutes(),
    "s+": this.getSeconds(),
    "q+": Math.floor((this.getMonth() + 3) / 3),
    "S": this.getMilliseconds()
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o) if (new RegExp("(" + k + ")").test(fmt)) 
    fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
  return fmt;
};

// 使用:new Date().Format("yyyy-MM-dd hh:mm:ss.S") → "2024-01-15 14:30:45.123"

8. 純數字校驗

function isDigit(value) {
  return /^\d+$/.test(value);
}

9. 設置 Cookie(含域名、路徑、過期時間)

function setCookie(name, value, hours) {
  var exp = new Date();
  exp.setTime(exp.getTime() + hours * 3600 * 1000);
  document.cookie = name + "=" + encodeURIComponent(value) + 
    ";expires=" + exp.toGMTString() + ";path=/;domain=yourdomain.com";
}

10. 讀取 Cookie

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

11. 加入收藏夾(跨瀏覽器兼容)

function AddFavorite(url, title) {
  try { window.external.addFavorite(url, title); } 
  catch(e) {
    try { window.sidebar.addPanel(title, url, ""); }
    catch(e) { alert("請使用 Ctrl+D 添加收藏"); }
  }
}

12. 設置首頁(IE/FF 兼容)

function setHomepage(url) {
  if (document.all) document.body.style.behavior = 'url(#default#homepage)';
  else if (window.sidebar) {
    try { netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); }
    catch(e) { alert("瀏覽器拒絕,請手動設置"); }
  }
}

13. IE6 圖片閃爍修復

if (navigator.userAgent.toLowerCase().indexOf("msie 6") > -1) {
  try { document.execCommand("BackgroundImageCache", false, true); } catch(e) {}
}

14. 動態加載 CSS

function LoadStyle(url) {
  var link = document.createElement('link');
  link.rel = 'stylesheet'; link.href = url;
  document.head.appendChild(link);
}

15. 提取腳本標籤內容(用於動態加載 JS)

function evalscript(s) {
  if (!/<script/i.test(s)) return s;
  var scripts = s.match(/<script[^>]*>([\s\S]*?)<\/script>/gi) || [];
  scripts.forEach(function(script) {
    var srcMatch = script.match(/src=["']([^"']+)["']/i);
    if (srcMatch) {
      // 動態加載外部腳本
      var s = document.createElement('script');
      s.src = srcMatch[1];
      document.head.appendChild(s);
    } else {
      // 執行內聯腳本
      eval(script.replace(/<\/?script[^>]*>/gi, ''));
    }
  });
  return s.replace(/<script[\s\S]*?<\/script>/gi, '');
}

後續 85 個函數將涵蓋:數組去重/扁平化、深拷貝、防抖節流、設備檢測、本地存儲封裝、AES 加密、Canvas 圖片壓縮、WebSocket 重連等進階主題。建議收藏備查,按需複製到項目工具庫。

copyright © 萬盛學電腦網 all rights reserved