项目中常用的js处理数据方法整理

1.数据千分位分隔处理

const formatNumValue = (num) => {
  let reg = /\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g;
  if(num === null || num === ""){
    return "-"
  }else{
    return String(num).replace(reg, ',');
  }
}

2.1文字拷贝,navigator.clipboard

 export const copyUrl = (url, type = 1) => {//复制链接
	if (type == 1) {
		navigator.clipboard
			.writeText(url)
			.then(() => {
				console.log("复制成功");
			})
			.catch(err => {
				console.log("复制失败", err);
			});
		return;
	}
};

2.2文字拷贝,创建input标签拷贝,兼容性问题:复制操作在chrome浏览器和360浏览器上是正常的,在QQ浏览器和UC浏览器上复制不成功,也不兼容ios

 export const copyUrl2 = (url) => {
    let input = document.createElement("input");
    input.value = url;
    document.body.appendChild(input);
    input.select();
    document.execCommand("copy");
    document.body.removeChild(input);
};

2.3文字复制,支持图片复制到微信,可兼容ios

copyText(){
   const range = document.createRange();
   range.selectNode(document.getElementById('img1'));
   const selection = window.getSelection();
   //移除之前选中内容
   if (selection.rangeCount>0) selection.removeAllRanges();
   selection.addRange(range);
   document.execCommand('copy');
   alert("复制成功!");
   selection.removeAllRanges()
 }

3.实现类知乎/掘金复制大段文本添加版权信息

document.body.oncopy = event => {
			event.preventDefault(); // 取消默认的复制事件
			let textFont = null
			let copyFont = window.getSelection().toString(); // 被复制的文字 等下插入
			// 防知乎掘金 复制一两个字则不添加版权信息 超过一定长度的文字 就添加版权信息
			if(copyFont.length > 10) {
				textFont =`
					${copyFont} 
					作者:codingWeb 
					链接:https://blog.csdn.net/fesfsefgs
					来源:csdn 
					著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。`
			} else {
				textFont = copyFont; // 没超过十个字 则采用被复制的内容。
			}
		   event.clipboardData.setData('text', textFont); // 将信息写入粘贴板
		};

4.实现类起点网的防复制功能

// 禁止右键菜单
document.body.oncontextmenu = e => {
    console.log(e, '右键');
    return false;
    // e.preventDefault();
};
// 禁止文字选择。
document.body.onselectstart = e => {
    console.log(e, '文字选择');
    return false;
    // e.preventDefault();
};
// 禁止复制
document.body.oncopy = e => {
    console.log(e, 'copy');
    return false;
    // e.preventDefault();
}
// 禁止剪切
document.body.oncut = e => {
    console.log(e, 'cut');
    return false;
    // e.preventDefault();
};
// 禁止粘贴
document.body.onpaste = e => {
    console.log(e, 'paste');
    return false;
    // e.preventDefault();
};
// css 禁止文本选择 这样不会触发js
body {
    user-select: none;
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
}

 5.获取url上的参数问题

//获取url上#后?后的参数,如:http://test.com/#/index?a=1
const getQueryString = (url, name) => {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  if (url.split("?")[1]) {
    url = url.split("#")[1];
    var r = url.split("?")[1].match(reg);
    if (r != null) return unescape(r[2]);
  }
  return null;
}
//获取url上#前?后的参数,如:http://test.com/?a=1#/index,#之前叫search,#之后叫hash,整个url叫href  
function getQueryString(url, name) {
let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
let param = window.location.search.substr(1)?window.location.search.substr(1).match(reg):null;
if(!param){
    param = window.location.href.substr(1)?window.location.href.substr(1).match(reg):null;
}
return param && param[2];
};

 6.普通number数组求和

let list = [1,2,3,4,5];
let count = list.reduce((cur,next)=>{
    return cur+(next);
},0);

7.数组扁平化处理

let list2 = [1,2,[3,4],[5,6,7]];
function fatter(array){
    return Array.isArray(array)?array.reduce((cur,next)=>{
        console.log('cur',cur);
        return cur.concat(Array.isArray(next)?fatter(next):next); 
    },[]):[]
}

8.普通数组去重

let a = [1,2,3,3];
let obj = [...new Set(a)];
console.log(obj);

9.对象数组去重,reduce循环,some判断条件是否为true

const uniqueObj = (arr, fn) =>arr.reduce((acc, v) => {if (!acc.some(x => fn(v, x))) acc.push(v);return acc;}, []);
 
uniqueObj([{id: 1, name: '大师兄'}, {id: 2, name: '小师妹'}, {id: 1, name: '大师兄'}], (a, b) => a.id == b.id)

10.通过图片url下载同源和不同源图片

 export function downBlobFile(url, fileName) {//下载同源图片
	const link = document.createElement("a");
	link.href = url;
	link.download = fileName;
	document.body.appendChild(link);
	link.click();
	window.setTimeout(function () {
	  document.body.removeChild(link);
	}, 0);
  }
export function downBlobFile2(url, fileName) {//下载不同源图片
	const x = new window.XMLHttpRequest();
	x.open("GET", url, true);
	x.responseType = "blob";
	x.onload = () => {
	  const url = window.URL.createObjectURL(x.response);
	  const a = document.createElement("a");
	  a.href = url;
	  a.target = "_blank";
	  a.download = fileName;
	  a.style.display = "none";
	  document.body.append(a);
	  a.click();
	};
	x.send();
  }

 11.时间戳返回时间信息对象(年月日时分秒),具体格式做调整

/*
入参 是一个 13位的, 以ms 为单位的 时间戳;
如果参数为空, 则使用当前时间
*/
let getTimeObj = (timestamp_ms) => {
    if (!timestamp_ms) {
        throw new Error('Error: getTimeObj func error, timestamp_ms 错误', timestamp_ms)
    }
    let date = new Date(timestamp_ms);
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    let hour = date.getHours();
    let min = date.getMinutes();
    let second = date.getSeconds();
    let week = date.getDay();
    let add0 = (value) => {
        return (value < 10 ? `0${value}` : value)
    }
    return {
        year,
        month: add0(month),
        day: add0(day),
        hour: add0(hour),
        min: add0(min),
        second: add0(second),
        week
    }
}

 12.数据类型判断

let type = value => {
	return Object.prototype.toString.call(value).slice(8).slice(0, -1).toLowerCase();
}

let isNumber = v => type(v) === 'number'
let isString = v => type(v) === 'string'
let isBoolean = v => type(v) === 'boolean';
let isBool = isBoolean;
let isFunction = v => type(v) === 'function';
let isObj = v => type(v) === 'object';
let isArray = v => type(v) === 'array';
let isUndefined = v => type(v) === 'undefined'
let isNull = v => type(v) === 'null'

export default type;
export {
	isNumber,
	isString,
	isBoolean,
	isBool,
	isFunction,
	isObj,
	isArray,
	isUndefined,
	isNull
}

 13.验证输入内容用到的正则表达式

// 验证需要用到的正则
export const notEmptyReg = new RegExp(/\S/); // 不为空
export const ruleReg1 = new RegExp(/^[\u4e00-\u9fa5a-zA-Z0-9()]+$/); // 中文、英文、数字,以及半角括号
export const ruleReg2 = new RegExp(/^[\u4e00-\u9fa5a-zA-Z0-9()::]+$/); // 汉字、数字、英文字母、半角括号、冒号
export const zhReg = new RegExp(/^[\u4e00-\u9fa5]{0,}$/); // 中文
export const enReg = new RegExp(/^[A-Za-z]+$/); // 英文字母
export const numberReg = new RegExp(/^[0-9]*$/); // 数字
export const specialSymbolReg = new RegExp(/^[$#+{}()()《》<>=\-\_——:?*&%|:。,、?!!/.,~@'"“”]+$/); // 常用特殊字符

参考链接:

添加版权信息,防复制功能:https://blog.csdn.net/fesfsefgs/article/details/111875639

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值