DIV CSS 佈局教程網

JavaScript 常用工具函式整理:字串、Cookie、日期與陣列
編輯:關於JavaScript     

在日常前端開發中,常會需要處理字串、Cookie、日期格式與陣列操作。以下整理幾個常用工具函式,方便查閱與 reuse。

字串長度截取

function cutStr(str, len) {
  var result = '';
  var count = 0;

  for (var i = 0; i !== str.length; i++) {
    var temp = str.substr(i, 1);
    if (/[^\x00-\xff]/.test(temp)) {
      count += 2;
    } else {
      count += 1;
    }

    if (count > len) {
      return result + '...';
    }
    result += temp;
  }

  return result;
}

取代全部字串

String.prototype.replaceAll = function(target, replacement) {
  return this.split(target).join(replacement);
};

清除左右空格

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

設定 Cookie

function setCookie(name, value, hours) {
  var expires = '';
  if (hours) {
    var date = new Date();
    date.setTime(date.getTime() + hours * 60 * 60 * 1000);
    expires = '; expires=' + date.toUTCString();
  }
  document.cookie = name + '=' + encodeURIComponent(value) + expires + '; path=/';
}

取得 Cookie

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

日期格式化

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).toString().padStart(2, '0'));
  str = str.replace(/MM/, (this.getMonth() + 1).toString().padStart(2, '0'));
  str = str.replace(/M/g, this.getMonth() + 1);
  str = str.replace(/w|W/g, week[this.getDay()]);
  str = str.replace(/dd|DD/, this.getDate().toString().padStart(2, '0'));
  str = str.replace(/d|D/g, this.getDate());
  str = str.replace(/hh|HH/, this.getHours().toString().padStart(2, '0'));
  str = str.replace(/h|H/g, this.getHours());
  str = str.replace(/mm/, this.getMinutes().toString().padStart(2, '0'));
  str = str.replace(/m/g, this.getMinutes());
  str = str.replace(/ss|SS/, this.getSeconds().toString().padStart(2, '0'));
  str = str.replace(/s|S/g, this.getSeconds());

  return str;
};

陣列去除重複

function unique(arr) {
  return Array.from(new Set(arr));
}

隨機數值

function randomRange(min, max) {
  return Math.round(Math.random() * (max - min) + min);
}

這些工具函式可以依專案需求調整。實際開發時,也可優先考慮 lodash、dayjs 等成熟工具庫,減少重複造輪子的成本。

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