常用的前端js整理代码
// 将所有的转义字符转成对应的特殊字符 const data = new DOMParser().parseFromString(contentData, text/html).body.textContent || ; // 数组去重,并按照从小到大排序 let arr = [1, 1, 2] arr = Array.from(new Set(arr)); // 去重 arr = arr.sort((a, b) => a - b); // 从小到大排序,arr.sort((a, b) => b - a)则降序
// 输入框禁止输入非数字
handleChange = (e) => {
const value = e.target.value;
const reg = /^-?d*(.d*)?$/;
if (!value) {
this.setState({compId: value});
} else if (reg.test(value) && value !== - && value.indexOf(.) === -1) {
this.setState({compId: value});
}
}
<input value={this.state.compId} onInput={this.handleChange} />
// 禁用当天之前的日期
disabledDate = (current) => {
current < moment().subtract(1, days);
}
<RangePicker disabledDate={this.disabledDate()} />
// RangePicker 禁用三个月以及七天写法
<RangePicker disableDate={this.disableDate} />
disableDate(time){
if(!time){
return false
}else{
return time<moment().subtract(3,month) || time>moment().add(3,m)//限制三个月
//return time<moment().subtract(7,day) || time>moment().add(7,day)//限制七天
}
// 获取当天日期(方法一)
componentDidMount() {
const date = new Date();
let nowMonth = date.getMonth() + 1;
let nowDay = date.getDate();
if (nowMonth >= 1 && nowMonth <= 9) {
nowMonth = `0${nowMonth}`
}
if (nowDay >= 1 && nowDay <= 9) {
nowDay = `0${nowDay}`
}
const nowDate = `${date.getFullYear()}-${nowMonth}-${nowDay}`;
}
// 获取当天日期(方法二,有时分秒)
componentDidMount() {
const startDay = dayjs().startOf(day).format(YYYY-MM-DD HH:mm:ss);
const endDay = dayjs().endOf(day).format(YYYY-MM-DD HH:mm:ss);
// 当天日期00:00:00到当天日期23:59:59
}
// 获取七天前日期(传0代表今天)
componentDidMount () {
this.handleGetDate(-6);
}
handleGetDate = num => {
const date1= new Date();
const date2 = new Date(date1);
date2.setDate(date1.getDate() + num);
// num是正数表示之后的时间,num负数表示之前的时间,0表示今天
return `${this.addZero(date2.getFullYear())}-${this.addZero(date2.getMonth() + 1)}-${this.addZero(date2.getDate())}`;
}
addZero = (num) => { //补0
if(Number(num) < 10){
return `0${num}`;
}
return num;
}
// 使用正则替换replaceAll const content = xxxxx1; const newContent = content.replace(/1/gi, x);
下一篇:
前端经典面试题(摘自牛客)
