当前位置:网站首页>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
边栏推荐
- Codeforces Round #784 (Div. 4) (A - H)题解
- Rhcsa day 4 operation
- Chapter V project quality management of information system project manager summary
- Day 3 of learning rhcsa
- 5W of knowledge points
- leangoo脑图-共享式多人协作思维导图工具分享
- C language 171 Number of recent palindromes
- 字符串去掉空格问题
- JVM class loader
- JZ35 replication of complex linked list
猜你喜欢

Leangoo brain map - shared multi person collaborative mind mapping tool

How big the program development of single chip microcomputer project can be, it represents your level of knocking code

C语言 171. 最近回文数

Domestic lightweight Kanban scrum agile project management tool

【unity3D】直播间滚动式弹幕效果

windows MySQL8 zip安装

Solve the problem that PowerShell mining occupies 100% of cpu7 in win7

1215_ Hello world used by scons

基于ele封装下拉菜单等组件

C language 171 Number of recent palindromes
随机推荐
MySQL function syntax
1215_ Hello world used by scons
《信息系统项目管理师总结》第六章 项目人力资源管理
The second day of learning rhcsa
Sonic cloud real machine tutorial
JZ35 replication of complex linked list
《信息系统项目管理师总结》第七章 项目沟通管理
Practice of industrial defect detection project (III) -- Based on FPN_ PCB defect detection of tensorflow
C language 171 Number of recent palindromes
【Hcip】OSPF常用的6种LSA详解
What is the difference between varchar and char?
JZ76 删除链表中重复的结点
Leangoo brain map - shared multi person collaborative mind mapping tool
ROP Emporium x86_ 64 7 ~ 8 questions
ROP Emporium x86_64 7~8题
Basic workflow of CPU
Classification and regression tree of machine learning
Source code and some understanding of employee management system based on polymorphism
Chapter V project quality management of information system project manager summary
PIP install shutil reports an error