JS极简代码片段

1,825次阅读

复制文本

// 复制文本到剪切板
const copyToClipboard = (text) => navigator.clipboard.writeText(text);
copyToClipboard('AlanWu.CC');

第几天

// 获取某个日期位于当前的第几天
const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(),0,0)) / 1000 / 60 / 60 /24);
console.log(dayOfYear(new Date(2022,10,28)));//332

解析 URL 参数

// 解析 URL 中的参数
const parseQuery = (url) => {q = {};
	url.replace(/([^?&=]+)=([^&]+)/g,
		(_,k,v) => (q[k]) = v
	);
	return q;
};
console.log(parseQuery('https://alanwu.cc/?s=js&date=20221128'));
console.log(parseQuery('s=js&date=20221128'));

对象属性筛选

// 筛选对象属性
const pick = (obj,...props) => Object.fromEntries(Object.entries(obj).filter(([k]) => props.includes(k))
);
console.log(pick({a:1,b:2,c:3},'a','c'));

随机颜色

// 随机 HEX 颜色方法一
const randomColor = () => '#' + Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6,'0');
console.log(randomColor());

// 随机 HEX 颜色方法二
const randomColor = () => `#${Math.random().toString(16).substr(2, 6)}`;    
console.log(randomColor());

//rgb 颜色随机
function rgb(){var r = Math.floor(Math.random()*256);
var g = Math.floor(Math.random()*256);
var b = Math.floor(Math.random()*256);
var rgb = '('+r+','+g+','+b+')';
return rgb;
}
console.log(rgb());

随机字符串

// 生成指定长度的随机字符串
const randomString = n => {
  let str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; 
  let temp = '';
  for(let i=0;i<n;i++){temp += str.charAt(Math.random()*35);
  }
  return temp;
}
console.log(randomString(8))

移除标记

// 移除字符串中的元素标记
const removeTag = (fragment) => new DOMParser().parseFromString(fragment,'text/html').body.textContent || '';
console.log(removeTag('<div>AlanWu.CC</div>'));

微信扫描下方的二维码阅读本文

JS 极简代码片段

 
Alan明宇
版权声明:本站原创文章,由 Alan明宇 2022-11-28发表,共计1449字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。