Last active
March 26, 2019 08:18
-
-
Save roshanca/fc4458332aeac55bc66d63cc37de2cdd to your computer and use it in GitHub Desktop.
实用工具
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 获取表单数据对象 | |
* | |
* @param {HTMLFormElement | string} form | |
* @return {object} | |
*/ | |
export const getFormData = form => { | |
let data = {} | |
const kvObjArray = $(form).serializeArray() | |
for (let obj of kvObjArray) { | |
if (data[obj.name]) { | |
// 多選 | |
data[obj.name] = [data[obj.name], $.trim(obj.value)].join(',') | |
} else { | |
data[obj.name] = $.trim(obj.value) | |
} | |
} | |
return data | |
} | |
/** | |
* 將 queryString 解析为对象 | |
* | |
* @param {string} search | |
* @return {object} | |
*/ | |
export const queryParse = (search = window.location.search) => { | |
if (!search) return {} | |
const queryString = search[0] === '?' ? search.substring(1) : search | |
const query = {} | |
queryString.split('&').forEach(queryStr => { | |
const [key, value] = queryStr.split('=') | |
/* istanbul ignore else */ | |
if (key) query[decodeURIComponent(key)] = decodeURIComponent(value) | |
}) | |
return query | |
} | |
/** | |
* 将对象转化为 queryString | |
* | |
* @param {object} query | |
* @return {string} | |
*/ | |
export const queryStringify = query => { | |
const queryString = Object.keys(query) | |
.map(key => `${key}=${encodeURIComponent(query[key] || '')}`) | |
.join('&') | |
return queryString | |
} | |
/** | |
* 去除 url 中特定的 queryString | |
* | |
* @param {string} key | |
* @param {string} href | |
* @return {string} | |
*/ | |
export const removeQueryString = (key, href = window.location.href) => { | |
const [url, search] = href.split( '?' ) | |
if (!search) { | |
return url | |
} | |
let queryString = search.split('&') | |
let finalQuery = '' | |
if (queryString.length) { | |
queryString = queryString.filter(item => !item.startsWith(key + '=')) | |
} | |
if (!queryString.length) { | |
return url | |
} | |
finalQuery = queryString.length > 1 ? queryString.join('&') : queryString[0] | |
return url + '?' + finalQuery | |
} | |
// 通用校验 | |
export const Verify = { | |
present(val) { | |
val = $.trim(val) | |
if (val === '') { | |
return false | |
} | |
return true | |
}, | |
isEmail(val) { | |
const reg = /^([a-zA-Z0-9_-])+%40([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/ | |
return reg.test(val) | |
} | |
} | |
// 防 XSS | |
export function escapeHtml(str) { | |
if (str.length === 0) return '' | |
let s | |
s = str.replace(/&/g, '&') | |
s = s.replace(/</g, '<') | |
s = s.replace(/>/g, '>') | |
s = s.replace(/ /g, ' ') | |
s = s.replace(/\'/g, ''') | |
s = s.replace(/\"/g, '"') | |
return s | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment