当前位置:网站首页>Regular object type conversion tool - Common DOM class
Regular object type conversion tool - Common DOM class
2022-04-23 02:53:00 【Diga】
Here's the catalog title
Regular judgment
Email judgment
function isEmail(email){
var emailReg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{
2,6}|[0-9]{
1,3})(\]?)$/;
if (emailReg2.test(email)){
return true;
}
else{
return false;
}
}
Mobile number judgment
function isMobile(mobile){
if ( mobile.length != 11 ){
return 0;
}
if( checkNUM(mobile) == 0){
return 0;
}
var s = mobile.substring(0,1);
if( s != "1"){
return 0;
}
return 1;
}
Check whether it is a function of numbers
// Check whether the number
function checkNUM(NUM)
{
var i,j,strTemp;
strTemp="0123456789";
if ( NUM.length== 0)
return 0
for (i=0;i<NUM.length;i++)
{
j=strTemp.indexOf(NUM.charAt(i));
if (j==-1)
{
return 0;
}
}
return 1;
}
Get the length of the field
function byteLength(str) {
// returns the byte length of an utf8 string
let s = str.length
for (var i = str.length - 1; i >= 0; i--) {
const code = str.charCodeAt(i)
if (code > 0x7f && code <= 0x7ff) s++
else if (code > 0x7ff && code <= 0xffff) s += 2
if (code >= 0xDC00 && code <= 0xDFFF) i--
}
return s
}
byteLength('https://www.baidu.com/s?ie=utf-8&f=8&rsv_b')
42
Name verification
static validateName(name) {
if(!(/^(?:[\u4e00-\u9fa5]+)(?:●[\u4e00-\u9fa5]+)*$|^[a-zA-Z0-9]+\s?[\.·\-()a-zA-Z]*[a-zA-Z]+$/.test(name))){
Util.showToast(' The name format is incorrect ',1000)
return
} else {
return true
}
}
Character substitution
var str=2020-3-11
str.replace(/-/g, "/");
2020/3/11
Type conversion
json turn params
function json2Param(json) {
if (!json) return ''
return cleanArray(
Object.keys(json).map(key => {
if (json[key] === undefined) return ''
return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
})
).join('&')
}
example
json2Param({
name:'wjg',age:18})
"name=wjg&age=18"
json become query
var format = function (val) {
val = val == null ? '' : val.toString().trim();
return encodeURIComponent(val);
}
function jsonToQuery(json) {
var query = [];
if (typeof json == 'object') {
for (var k in json) {
if (k === '$nullName') {
query = query.concat(json[k]);
continue;
}
if (json[k] instanceof Array) {
for (var i = 0, len = json[k].length; i < len; i++) {
query.push(k + '=' + format(json[k][i]));
}
} else {
if (typeof json[k] != 'function') {
query.push(k + '=' +format(json[k]));
}
}
}
}
if (query.length) {
return query.join('&');
} else {
return '';
}
}
Example :
var json = {
id: 1, name: 'benny' };
jsonToQuery(json, true)
"id=1&name=benny"
html turn written words
function html2Text(val) {
const div = document.createElement('div')
div.innerHTML = val
return div.textContent || div.innerText
}
html2Text('<div>111111</div>')
"111111"
html2Text('<div>123</div>')
"123"
Get the parameters of the address
params turn obj
export function getQueryObject(url) {
url = url == null ? window.location.href : url
const search = url.substring(url.lastIndexOf('?') + 1)
const obj = {
}
const reg = /([^?&=]+)=([^?&=]*)/g
search.replace(reg, (rs, $1, $2) => {
const name = decodeURIComponent($1)
let val = decodeURIComponent($2)
val = String(val)
obj[name] = val
return rs
})
return obj
}
eg:
getQueryObject('https://www.baidu.com/s?wd=%E9%98%BF%E8%90%A8&ie=utf-8&tn=68018901_7_oem_dg')
{
wd: " ASAR ", ie: "utf-8", tn: "68018901_7_oem_dg"}
getQueryObject('adasdsa?name=wang&age=18')
{
name: "wang", age: "18"}
function param2Obj(url) {
const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
if (!search) {
return {
}
}
const obj = {
}
const searchArr = search.split('&')
searchArr.forEach(v => {
const index = v.indexOf('=')
if (index !== -1) {
const name = v.substring(0, index)
const val = v.substring(index + 1, v.length)
obj[name] = val
}
})
return obj
}
param2Obj('https://www.google.com/search?q=%E8%AF%95%E8%AF%95')
{
q: " try "}
DOM object
Object add delete class name
function toggleClass(element, className) {
if (!element || !className) {
return
}
let classString = element.className
const nameIndex = classString.indexOf(className)
if (nameIndex === -1) {
classString += '' + className
} else {
classString =
classString.substr(0, nameIndex) +
classString.substr(nameIndex + className.length)
}
element.className = classString
}
let head = document.getElementById("head");
toggleClass(head,'baidu')
Determine whether the object is empty
function isEmptyObject(e) {
var t;
for (t in e)
return false;
return true;
};
isEmptyObject({}) //true
isEmptyObject('') //true
isEmptyObject(undefined); //true
Judgment type
Check the incoming object
- If it is null Then return to null(typeof null Is to return object)
- If it is an array, it returns array(typeof [] Is to return object)
function getType(obj) {
var type;
return ((type = typeof (obj)) == 'object' ? obj == null && 'null' || Object.prototype.toString.call(obj).slice(8, -1) : type).toLowerCase();
}
example :
getType({
})
"object"
getType([])
"array"
getType('aa')
"string"
getType(null)
"null"
getType(undefined)
"undefined"
Import file judgment
dataType.js
export const getType = obj => Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
export const isNumber = obj => getType(obj) === "number";
export const isString = obj => getType(obj) === "string";
export const isArray = obj => getType(obj) === "array";
export const isObject = obj => getType(obj) === "object";
export const isBoolean = obj => getType(obj) === "boolean";
export const isFunction = obj => getType(obj) === "function";
export const isNull = obj => getType(obj) === "null";
export const isUndefined = obj => getType(obj) === "undefined";
export const isPromise = obj => getType(obj) === "promise";
export const isNode = node => !isNull(node) && !isUndefined(node) && Boolean(node.nodeName) && Boolean(node.nodeType);
export const isElement = element => isNode(element) && element.nodeType === 1;
import {
isObject } from './dataType'
Judge whether it is the object
let bool = isObject(html);
// Whether there are nodes node
import {
isNode} from './dataType'
if(!isNode(this.node)) return;
Merge objects
function merge(obj1, obj2) {
if (getType(obj1) != 'object' || getType(obj2) != 'object') {
console.error(' The parameters passed in must all be objects ');
return;
}
var newObj = {
};
for (var key1 in obj1) {
newObj[key1] = obj1[key1];
}
for (var key2 in obj2) {
newObj[key2] = obj2[key2];
}
return newObj;
}
eg:
merge({
a:1},{
b:2})
{
a: 1, b: 2}
merge({
a:1},{
b:2,a:2})
{
a: 2, b: 2}
eg:
var opts = {
url: 'http://www.baidu.com' };
var defaultOpts = {
url: '', method: 'get' };
opts = merge(defaultOpts, opts);
{
url: "http://www.baidu.com", method: "get"}
Delete empty objects
function dealObjectValue(obj) {
var param = {
};
if ( obj === null || obj === undefined || obj === "" ) return param;
for ( var key in obj ){
if( obj[key] !== null && obj[key] !== undefined && obj[key] !== "" ){
param[key] = obj[key];
}
}
return param;
}
eg:
dealObjectValue({
name:'wangji',age:''})
{
name: "wangji"}
Clear empty array data
function cleanArray(actual) {
const newArray = []
for (let i = 0; i < actual.length; i++) {
if (actual[i]) {
newArray.push(actual[i])
}
}
return newArray
}
eg:
cleanArray(['11','22',''])
["11", "22"]
cleanArray(['11','22',undefined])
["11", "22"]
Function throttling
Within one unit time , Function can only be triggered once . If multiple functions are triggered in this unit time , Only once .
Method 1 :
function throttle(fn, gapTime) {
if (gapTime == null || gapTime == undefined) {
gapTime = 1500
}
let _lastTime = null
// Return the new function
return function () {
let _nowTime = +new Date()
if (_nowTime - _lastTime > gapTime || !_lastTime) {
fn.apply(this, arguments) // take this And parameters to the original function
_lastTime = _nowTime
}
}
}
eg:
import util from "@/utils/util"
clickHandle: util.throttle(function() {
...
}, 2000),
Method 2 :
export function throttle(fn, wait) {
let previous = 0
return function (...args) {
const now = Date.now()
if ((now - previous) > wait) {
fn.apply(this, args)
previous = now
}
}
}
eg:
onceClick:throttle(function(){
...
},1000),
static throttle(func, delay){
var timer = null;
return function(){
var context = this;
var args = arguments;
if(!timer){
timer = setTimeout(function(){
func.apply(context, args);
timer = null;
},delay);
}
}
}
onceClick: throttle(function() {
....
}, 100),
Function anti shake
When the event is triggered n Seconds before the callback , If in n Executed again within seconds , Then the time will be counted again .
After adding anti shake , When you're typing frequently , It doesn't send requests , Only if you don't enter in the specified interval , To execute functions . be used for input Frame majority
export const debounce = (func, wait, immediate) => {
let timeout
return function () {
let context = this
let args = arguments
if (timeout) {
clearTimeout(timeout)
}
if (immediate) {
let callNow = !timeout
timeout = setTimeout(() => {
timeout = null
}, wait)
if (callNow) {
typeof func === 'function' && func.apply(context, args)
}
} else {
timeout = setTimeout(() => {
typeof func === 'function' && func.apply(context, args)
}, wait)
}
}
}
eg:
onClick={
debounce(() => handlefn(), 1000)}
版权声明
本文为[Diga]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220717433378.html
边栏推荐
- 期中汇总(概论+应用层+运输层)
- [unity3d] rolling barrage effect in live broadcasting room
- Devil cold rice 𞓜 078 devil answers the market in Shanghai and Nanjing; Communication and guidance; Winning the country and killing and screening; The purpose of making money; Change other people's op
- 解决win7 中powershell挖矿占用CPU100%
- 基于Scrum进行创新和管理
- Classification of technology selection (2022)
- JS using the parameters of art template
- Interim summary (Introduction + application layer + transportation layer)
- Processes and threads
- MySQL复杂查询使用临时表/with as(类似表变量)
猜你喜欢
Interim summary (Introduction + application layer + transportation layer)
Machine learning (Zhou Zhihua) Chapter 14 probability graph model
国产轻量级看板式Scrum敏捷项目管理工具
leangoo脑图-共享式多人协作思维导图工具分享
基于Scrum进行创新和管理
JVM class loader
How to build an integrated industrial Internet plus hazardous safety production management platform?
Practical combat of industrial defect detection project (II) -- steel surface defect detection based on deep learning framework yolov5
Interpretation of the future development of smart agriculture
Huawei machine test question -- deformation of hj53 Yang Hui triangle
随机推荐
【工欲善其事必先利其器】论文编辑及文献管理(Endnote,Latex,JabRef ,overleaf)资源下载及使用指南
Those years can not do math problems, using pyhon only takes 1 minute?
Résumé du gestionnaire de projet du système d'information Chapitre VI gestion des ressources humaines du projet
Basic workflow of CPU
Planning code ROS migration POMDP prediction planning (I)
【Hcip】OSPF常用的6种LSA详解
Efficient music format conversion tool Music Converter Pro
php+mysql对下拉框搜索的内容修改
Learn regular expression options, assertions
Practice of industrial defect detection project (III) -- Based on FPN_ PCB defect detection of tensorflow
工业互联网+危化安全生产综合管理平台怎样建
接口请求时间太长,jstack观察锁持有情况
Centos7 install MySQL 8 0
PIP install shutil reports an error
Winsock programming interface experiment: implementation of ipconfig
Chapter V project quality management of information system project manager summary
Kubernetes - Introduction to actual combat
The penultimate K nodes in jz22 linked list
Practical combat of industrial defect detection project (II) -- steel surface defect detection based on deep learning framework yolov5
Modify the content of MySQL + PHP drop-down box