在日常前端開發中,常會需要處理字串、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, '');
};
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=/';
}
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 等成熟工具庫,減少重複造輪子的成本。