1.获取浏览器地址栏?后的所有参数
1. 获取所有
getUrlParams = (url) => {
let str = url;
const num = str.indexOf("?");
str = str.substr(num + 1);
if (!str) {
return {};
}
const params = {};
const arr = str.split("&");
for (let i = 0; i < arr.length; i += 1) {
if (arr[i]) {
const keys = arr[i].split("=");
const value = keys[1];
params[keys[0]] = value;
}
}
return params;
};
const testUrl =
`http://219.232.216.237/hotline-app/?origin=1&t=${Date.parse(new Date()) / 1000}`;
const params = this.getUrlParams(testUrl);
2. 获取单个
export function getUrlParam(name) {
let urlArr = window.location.href.split('?')
if (urlArr.length < 2) {
return ''
}
let tempArr = urlArr[1].split('&')
for (let i = 0; i < tempArr.length; i++) {
let item = tempArr[i].split('=')
if (item[0].trim() == name) {
return item[1]
}
}
return ''
}
2.日期时间相关
1. 获取当天
getCurrentDate=()=>{
const date = new Date()
const year = String(date.getFullYear())
const month = date.getMonth() + 1 >= 10 ? date.getMonth() + 1 : `0${date.getMonth() + 1}`
const day = date.getDate() >= 10 ? date.getDate() : `0${date.getDate()}`
return `${year}/${String(month)}/${String(day)}`
}
2. 获取年月日 时分秒
const GetfullDateFormat = (time) => {
let now = new Date()
if (time) { now = new Date(time) }
const year = now.getFullYear();
const month = now.getMonth()+ 1< 10?`0${now.getMonth() + 1}`: now.getMonth() + 1
const date = now.getDate() < 10 ? `0${now.getDate()}` : now.getDate()
const hour = now.getHours() < 10 ? `0${now.getHours()}` : now.getHours()
const minute = now.getMinutes() < 10 ? `0${now.getMinutes()}` : now.getMinutes()
const second = now.getSeconds() < 10 ? `0${now.getSeconds()}` : now.getSeconds()
return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
}
3. 比较2时间
var startTime = new Date(date)
var endTime = new Date(date1)
if (startTime.getTime() - endTime.getTime() < 0) {
console.log('通过', data.getTime(), data1.getTime())
} else {
this.$message.warning('结束时间要大于开始时间!')
}
4.日期组件-不可选择范围的运用
<j-date
v-decorator="['fdEndDate', validatorRules.fdEndDate]"
placeholder="请选择服务结束时间"
:showTime="true"
:dateFormat="dateFormat"
@change="handleDateChange"
:value="fdEndDate"
:disabled-date="disabledDate"
/>
disabledDate(current) {
const test00 = moment(this.fdStartDate, 'YYYY-MM-DD HH:mm:ss').add(10, 'minutes')
const test11 = moment(this.fdStartDate, 'YYYY-MM-DD HH:mm:ss').endOf('day')
return current < test00 || current > test11
}
disabledStartDate(current) {
let disabledMoment = moment(this.fdStartDate, 'YYYY-MM-DD HH:mm:ss')
let date = moment(this.fdStartDate).format('YYYY-MM-DD')
let result = `${date} 23:59:59`
return current < disabledMoment || current > moment(result)
}
5.moment.js封装时间参数
setParams = type => {
const { defaultYear,defaultMonth,defaultDay,beginDate,endDate } = this.state
let paramObj = {}
if (type === '按日' || type === '本日') {
paramObj = {
fdDateType: 1,
fdYear: defaultYear,
fdMonth: defaultMonth,
fdDay: defaultDay,
beginFdDateid: '',
endFdDateid: ''
}
} else if (type === '上一日') {
const m = moment().subtract(1, 'days')
paramObj = {
fdDateType: 1,
fdYear: m.format('YYYY'),
fdMonth: m.format('MM'),
fdDay: m.format('DD'),
beginFdDateid: '', endFdDateid: ''
}
} else if (type === '下一日') {
const m = moment().add(1, 'days')
paramObj = {
fdDateType: 1,
fdYear: m.format('YYYY'),
fdMonth: m.format('MM'),
fdDay: m.format('DD'),
beginFdDateid: '', endFdDateid: ''
}
} else if (type === '按年-月' || type === '当月') {
paramObj = {
fdDateType: 2, fdYear: defaultYear,fdMonth: defaultMonth,fdDay: '',beginFdDateid: '',endFdDateid: ''}
} else if (type === '上一月') {
const m = moment().year(defaultYear).month(defaultMonth - 1).subtract(1, 'month')
paramObj = {
fdDateType: 2,
fdYear: m.format('YYYY'),
fdMonth: m.format('MM'),
fdDay: '',
beginFdDateid: '',
endFdDateid: ''
}
} else if (type === '下一月') {
const m = moment().year(defaultYear).month(defaultMonth - 1).add(1, 'month')
paramObj = {fdDateType:2,fdYear:m.format('YYYY'),fdMonth:m.format('MM'),fdDay:'',beginFdDateid:'',endFdDateid:''}
} else if (type === '自定义') {
paramObj = {fdDateType: 1,fdYear: '',fdMonth: '',fdDay: '',beginFdDateid: beginDate,endFdDateid: endDate }
}
return paramObj
}
6.计算时间差
timeFn = params => {
let dateBegin = new Date(params.replace(/-/g, "/"));
let dateEnd = new Date();
let dateDiff = dateEnd.getTime() - dateBegin.getTime();
let dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000));
let leave1 = dateDiff % (24 * 3600 * 1000);
let hours = Math.floor(leave1 / (3600 * 1000));
hours = hours < 10 ? `0${hours}` : hours;
let leave2 = leave1 % (3600 * 1000);
let minutes = Math.floor(leave2 / (60 * 1000));
minutes = minutes < 10 ? `0${minutes}` : minutes;
let leave3 = leave2 % (60 * 1000);
let seconds = Math.round(leave3 / 1000);
seconds = seconds < 10 ? `0${seconds}` : seconds;
if (dayDiff >= 1) {
hours = Number(dayDiff) * 24 + Number(hours);
}
this.setState({ hours: hours, minutes: minutes, seconds: seconds });
};
3. 身份证号的加密&根据身份证号获取年龄、性别
const idCardEncry = function (idCard) {
let newIdCard = "";
if (idCard) {
const start = idCard.substring(0, 6);
const center = "******";
const last = idCard.substring(idCard.length - 4);
newIdCard = start + center + last;
}
return newIdCard;
};
getGenderAge(IdCard, type) {
if (type === 1) {
let birthday = IdCard.substring(6, 10) + "-" + IdCard.substring(10, 12) + "-" + IdCard.substring(12, 14)
return birthday
}
if (type === 2) {
if (parseInt(IdCard.substr(16, 1)) % 2 === 1) {
return "男"
} else {
return "女"
}
}
if (type === 3) {
var birthDay = IdCard.substring(6, 14);
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth() + 1 < 10 ? `0${now.getMonth() + 1}` : now.getMonth() + 1;
var date = now.getDate() < 10 ? `0${now.getDate()}` : now.getDate();
var time = year + "-" + month + "-" + date
var yearStr = time.split("-")[0];
var monthStr = time.split("-")[1];
var dayStr = time.split("-")[2];
var yearBirthStr = birthDay.substring(0, 4);
var monthBirthStr = birthDay.substring(4, 6);
var dayBirthStr = birthDay.substring(6);
var year = yearStr;
var yearBirth = yearBirthStr;
if (year - yearBirth <= 0) {
return 0;
}
var age = year - yearBirth;
var month = monthStr;
var monthBirth = monthBirthStr;
if (month - monthBirth > 0) {
return age;
}
if (month - monthBirth < 0) {
return --age;
}
var day = dayStr;
var dayBirth = dayBirthStr;
if (day - dayBirth >= 0) {
return age;
}
return --age;
}
}
4.正则表达式相关
1. 驼峰英文遇到大写字母转小写并前面+下划线
const str = 'goodsCommonName'
str.replace(/([A-Z])/g, "_$1").toLowerCase()
2.手机号码验证
const patt = /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/;
使用:if(!this.patt.test(phone)){ this.$message.error('请输入正确的联系方式!') }
3.身份证号校验&脱敏
checkCard = (value) => {
let reg = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;
if (reg.test(value)) {
return true
} else {
return false
}
}
checkFdCard = (card) => {
if (card) {
return card.replace(/^(.{4}).+(.{4})$/, "$1********$2")
} else { return ''}
}
4. 数字值允许0的验证
checkIsNull(str) {
if (str === 0) {
return true
}
return !str ? false : true
}
5.校验姓名
checkFdName = (fdName) => {
let reg = /^[A-Za-z\u4e00-\u9fa5]{2,10}$/;
if (reg.test(fdName)) {
return true
} else {
return false
}
}
6.电话号码加密展示
const phoneObj = phone => {
phone = phone || ''
if (phone) {
phone = "" + phone;
var reg = /(\d{3})\d{4}(\d{4})/;
var phone = phone.replace(reg, "$1****$2")
}
return phone
}
7.校验北京通、一卡通卡号
checkBjtCard = (value) => {
let reg = /\b\d{12}\b/;
if (reg.test(value)) {
return true
} else {
return false
}
}
checkYktCard = (value) => {
let reg = /\b\d{20}\b/;
if (reg.test(value)) {
return true
} else {
return false
}
}
8.校验银行卡号
checkBankCard = (value) => {
let reg = /^([6][2][1])(\d{16})$/;
if (reg.test(value)) {
return true
} else {
return false
}
}
5.数组数据-正序 倒序
ascSortData = (list, key) => {
const newList = list.sort((a, b) => {
if (a[key] >= b[key]) {
return 1;
}
return -1;
});
return newList;
};
export const descSortData = (list, key) => {
return list.sort((a, b) => {
if (a[key] > b[key]) {
return -1;
}
return 1;
});
};
6.数据不足几位数时,前面补0
export const padStart = (n, str) => {
return Array(str.length >= n ? 0 : n - str.length + 1).join('0') + str
}
mapTop3Total.map(itm => {
return padStart(4, String(itm.value)).split('')
})
7.移除script标签
function setTabScript() {
var script = document.createElement("script");
script.src = tab === 0 ? './js/report.js?v=2' : './js/report-weekly.js?v=2';
script.id = tab === 0 ? 'script01' : 'script02';
document.getElementsByTagName("body")[0].appendChild(script);
if (tab === 0) {
$('.h5').css('display', 'block')
}
}
$('.tab-item').each(function (i, v) {
if (tab === i) {
$(v).addClass('active')
$(v).siblings(".tab-item").removeClass("active");
}
$(v).click(function () {
tab = i
$(this).addClass('active')
$(this).siblings(".tab-item").removeClass("active");
currentDate = getCurrentDate()
$('#calendarInput').html(currentDate)
$('.body-weekly').css("display", i === 0 ? 'none' : 'block')
$('.body-daily').css("display", i === 0 ? 'block' : 'none')
if (i === 0) {
getAjax()
} else {
getWeeklyAjax()
}
isIncludeScript('script02')
isIncludeScript('script01')
})
})
function isIncludeScript(scriptId) {
var scriptElement = document.getElementById(scriptId);
if (scriptElement && scriptElement.readyState === 'complete') {
scriptElement.parentNode.removeChild(scriptElement);
} else if (!scriptElement) {
} else {
scriptElement.parentNode.removeChild(scriptElement);
}
}
8.解决跨域(浏览器配置)
http-proxy-middleware
chrome.exe
目标:"C:\Program Files\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir=C:\MyChromeDevUserData
9.判断一个对象是否是空对象
function isEmptyObject(obj) {
return Object.keys(obj).length === 0;
}
function isEmptyObject(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
return false;
}
}
return true;
}
function isEmptyObject(obj) {
return JSON.stringify(obj) === '{}';
}
10.获取IE的版本
function getIEVersion() {
var ua = window.navigator.userAgent;
var msie = ua.indexOf('MSIE ');
if (msie > 0) {
return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie), 10));
}
var trident = ua.indexOf('Trident/');
if (trident > 0) {
var rv = ua.indexOf('rv:');
return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv), 10));
}
return -1;
}
function getIEVersion() {
var userAgent = window.navigator.userAgent;
var versionFlag = ''
var isIE =
userAgent.indexOf("compatible") > -1 &&
userAgent.indexOf("MSIE") > -1;
var isEdge = userAgent.indexOf("Edge") > -1 && !isIE;
var isIE11 =
userAgent.indexOf("Trident") > -1 &&
userAgent.indexOf("rv:11.0") > -1;
if (isIE) {
var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
reIE.test(userAgent);
var fIEVersion = parseFloat(RegExp["$1"]);
versionFlag = fIEVersion;
} else if (isEdge) {
versionFlag = "edge";
} else if (isIE11) {
versionFlag = 11
} else {
versionFlag = -1
}
return versionFlag
}
11.根据host主机判断是ip还是域名
function isIPAddress(input) {
var ipRegex = /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/;
return ipRegex.test(input);
}
function checkAddressType() {
var input = window.location.hostname;
if (isIPAddress(input)) {
return 'ip';
} else {
return 'yuming';
}
}
12.富文本-去除所有html标签,只保留文字
function removeAllHtmlReg(text){
var reg=/<\/?.+?\/?>/g
var removed = text.replace(reg, '')
var reg01 = /[“,”, ,\s]+/g
var removed01 = removed.replace(reg01, '')
return removed01
}
var intro = removeAllHtmlReg(v.fd_content)
var keywordIndex = intro.indexOf(substr)
var slicedText = ''
if(keywordIndex>10){
slicedText = intro.substr(keywordIndex-10)
}else{
slicedText = intro.substr(keywordIndex)
}
if(slicedText.length >= 139){
slicedText = slicedText.substr(0,138) + '...';
}
var introductionStr = slicedText ? slicedText.replace(new RegExp(substr, 'gi'), function(match){
return "<strong class=highlight>"+match+"</strong>"
}):'';
relaceContent = (content)=>{
let result = ''
var reg01 = /<strong /gi
result = content.replace(reg01, '<span ')
return result
}
13.下载文件
1.blob+创建a标签
function downFile(url, fileName) {
$.ajax({
url: url,
type: "GET",
responseType: "blob",
success: function (blobData) {
var url = window.URL.createObjectURL(new Blob([blobData]));
var link = document.createElement("a");
link.style.display = "none";
link.href = url;
link.setAttribute("download", fileName);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
},
error: function (err) {
console.log("下载文件失败", err);
},
});
}
2.a标签(超链接)方式
renderFilesHtml = ()=>{
const {detailObj} = this.state
const fileList = detailObj.fdAnnex && detailObj.fdAnnex.split(',')
const html = fileList.map(x=>{
var fileName = x.split('/')[1]
const url = ImgUrl + x
const index01 = fileName.indexOf('_')
const index02 = fileName.indexOf('.')
const cut = fileName.slice(index01,index02)
const cutedFileName = fileName.replace(cut,'')
return (
<p onClick={()=>this.downLoadFile(url, fileName)}>{cutedFileName}</p>
)
})
return html
}
downLoadFile = (url, fileName) =>{
const eleLink = document.createElement('a');
eleLink.style.display = 'none';
eleLink.href = url;
document.body.appendChild(eleLink);
eleLink.click();
document.body.removeChild(eleLink);
}
14.react页面回到顶部功能
class DtywDetail extends Component {
constructor(props) {
super(props);
this.state={
detailObj:{},
isShowGoTop:false,
mainHeight:0,
loading: true
}
this.mainRef = React.createRef();
}
componentDidMount() {
this.getData(this.id)
window.addEventListener('scroll', this.HandleScroll, true)
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleScroll);
}
HandleScroll = ()=>{
const { mainHeight } = this.state
if(mainHeight >= 300 && window.scrollY >= 300){
this.setState({ isShowGoTop: true })
}else{
this.setState({ isShowGoTop: false })
}
}
goTop = ()=>{
document.body.scrollTop = document.documentElement.scrollTop = 0
}
goTopPosition = ()=>{
let scrollHeight = document.body.scrollHeight
let windowHeight = window.innerHeight
let maxSroll = scrollHeight-windowHeight
let str = '30px'
if(maxSroll - window.scrollY <= 240){
str = '300px'
}
return str
}
<div className='goTop' style={{ display: isShowGoTop ? 'block':'none', bottom: this.goTopPosition() }} onClick={()=>this.goTop()}><img src={goTopIcon} /></div>
15.react中解析富文本
relaceContent = (content)=>{
let result = ''
var reg01 = /<strong /gi
result = content.replace(reg01, '<span ')
return result
}
{ detailObj.fdContent && (
<div className="content">
<div
dangerouslySetInnerHTML={{
// __html: detailObj.fdContent
__html: this.relaceContent(detailObj.fdContent)
}}
/>
</div>
) }
16.