工具方法
yuhuo2021-08-05JavaScriptJavaScript代码片段
uuid()
/**
* 生成uuid,示例:() => "5e274a7d-0ed1-4abd-8ea4-f1dc028ae17d"
* @return {String} uuid字符串
**/
let uuid = function() {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
const r = (Math.random() * 16) | 0,
v = c == "x" ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
};
parseUrl()
/**
* url字符串转url对象,示例:("https://yuhuo.com/look?a=1#b") =>
* {
* protocol: "https:",
* host: "yuhuo.com",
* origin: "https://yuhuo.com",
* pathname: "/look",
* search: "?a=1",
* hash: "#b"
* }
* @param {String} url url字符串
* @return {Object} url对象
**/
let parseUrl = function(url) {
const aEle = document.createElement("a");
aEle.href = url;
let data = {
protocol: aEle.protocol,
host: aEle.host,
origin: aEle.origin,
pathname: aEle.pathname,
search: aEle.search,
hash: aEle.hash,
};
aEle.remove();
return data;
};
parseParams()
/**
* 参数字符串转参数对象,示例:("a=1&b=2") => {a: "1", b: "2"}
* @param {String} params 参数字符串
* @return {Object} 参数对象
**/
let parseParams = function(params) {
let obj = {};
params.replace(/([^?&=]+)=([^&]+)/g, (_, k, v) => (obj[k] = v));
return obj;
};
stringifyParams()
/**
* 参数对象转参数字符串,示例:({a: 1, b: 2}) => "a=1&b=2"
* @param {Object} params 参数对象
* @return {String} 参数字符串
**/
let stringifyParams = function(params) {
let str = "";
for (let key in params) {
str += "&" + key + "=" + params[key];
}
return str.substring(1);
};
copyText()
/**
* 复制文本
* @param {String} text 待复制文本
* @return {Boolean} 是否复制成功
**/
let copyText = function(text) {
const $input = document.createElement("input");
document.body.appendChild($input);
$input.value = text;
$input.select();
const result = document.execCommand("copy");
$input.remove();
return result;
};