Mainly organize some common Js code commonly used in daily work, in order to facilitate the recording and use.
- 1. Intercepts a string with a specified number of bytes
- 2. Determine whether wechat is available
- 3. Get some examples of time formats
- 4. Obtain the string length in bytes
- 5. Clone and deep copy objects
- 6. Verification of organizational structure code
- 7. Verification of ID number
- 8. The js re adds HTTP identifiers to the URL
- 9. Verify URL validity
- 10. Customize jSONP methods
- 11. A cookie
- 12. Generate random string (optionally length)
- 13. Browser judgment
- 14.Rem mobile adaptation
- 15. Obtain parameters after the URL
- Dynamic loading of JS
- 17. Generate random color values
- 18. Event binding and unbinding
- 19. Audio playback on mobile terminal
- 20. Mobile video adaptation
- 21.Webpack+Vue-CLI implementation of automatic global registration components
- 22. Precision calculation
- 23. Unify social credit codes
1. Intercepts a string with a specified number of bytes
/** * intercepts a string of specified bytes *@param STR intercepts the character through *@param Len The length to intercept, in bytes *@param Suffix Is the replacement of the first len characters with other characters. Generally, "... "is used. *@returns {*}* /
function cutString(str,len,suffix){
if(! str)return "";
if(len <= 0) return "";
if(! suffix) suffix ="";
var templen = 0;
for(var i = 0; i < str.length; i++){if(str.charCodeAt(i) > 255){
templen += 2;
}else{
templen++
}
if(templen == len){
return str.substring(0, i+1) + suffix;
}else if(templen > len){
return str.substring(0, i) + suffix; }}return str;
}
Copy the code
2. Determine whether wechat is available
/** * Check wechat browser *@returns {Boolean}* /
function isWeiXin() {
var ua = window.navigator.userAgent.toLowerCase();
if (ua.match(/MicroMessenger/i) = ='micromessenger') {
return true;
} else {
return false; }}Copy the code
3. Get some examples of time formats
function getTimeFormat(time){
var date = new Date(parseInt(time) * 1000);
var month,day,hour,min;
parseInt(date.getMonth())+1<10? month ='0'+ (parseInt(date.getMonth())+1):month = parseInt(date.getMonth())+1;
date.getDate()<10? day ='0'+date.getDate():day = date.getDate();
date.getHours()<10? hour ='0'+date.getHours():hour = date.getHours();
date.getMinutes()<10? min ='0'+date.getMinutes():min = date.getMinutes();
return [month, day].join(The '-') +' '+hour+':'+min
}
function getTimeFormatYMD(time) {
var date = new Date(parseInt(time) * 1000);
var year, month,day;
year = date.getFullYear();
parseInt(date.getMonth())+1<10? month ='0'+ (parseInt(date.getMonth())+1):month = parseInt(date.getMonth())+1;
date.getDate()<10? day ='0'+date.getDate():day = date.getDate();
return [year, month, day].join(The '-')}function getTimeFormatAll(time) {
var date = new Date(parseInt(time) * 1000);
var year, month,day,hour,min, second;
year = date.getFullYear();
parseInt(date.getMonth())+1<10? month ='0'+ (parseInt(date.getMonth())+1):month = parseInt(date.getMonth())+1;
date.getDate()<10? day ='0'+date.getDate():day = date.getDate();
date.getHours()<10? hour ='0'+date.getHours():hour = date.getHours();
date.getMinutes()<10? min ='0'+date.getMinutes():min = date.getMinutes();
date.getSeconds()<10? second ='0'+date.getSeconds():second = date.getSeconds();
return [year, month, day].join(The '-') +' '+hour+':'+min+':'+second
}
Copy the code
4. Obtain the string length in bytes
/** * gets the string length in bytes *@param {String}
* @returns {Boolean}* /
function checkLength(v){
var realLength = 0;
var len = v.length;
for (var i = 0; i < len; i++) {
var charCode = v.charCodeAt(i);
if (charCode >= 0 && charCode <= 128)
realLength += 1;
else
realLength += 2;
}
return realLength;
}
Copy the code
5. Clone and deep copy objects
/** * Object clone & deep copy *@param obj
* @returns {{}} * /
function cloneObj(obj) {
var newO = {};
if (obj instanceof Array) {
newO = [];
}
for (var key in obj) {
var val = obj[key];
newO[key] = typeof val === 'object' ? arguments.callee(val) : val;
}
return newO;
};
Copy the code
Clone copy enhanced versionCopy the code
/** * Object clone & deep copy *@param obj
* @returns {{}} * /
function clone(obj) {
// Handle the 3 simple types, and null or undefined
if (null == obj || "object"! =typeof obj) return obj;
// Handle Date
if (obj instanceof Date) {
var copy = new Date(a); copy.setTime(obj.getTime());return copy;
}
// Handle Array
if (obj instanceof Array) {
var copy = [];
for (var i = 0, len = obj.length; i < len; ++i) {
copy[i] = clone(obj[i]);
}
return copy;
}
// Handle Object
if (obj instanceof Object) {
var copy = {};
for (attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
}
return copy;
}
throw new Error("Unable to copy obj! Its type isn't supported.");
}
Copy the code
Test cases:Copy the code
var origin = {
a: "text".b: null.c: undefined.e: {
f: [1.2]}}Copy the code
6. Verification of organizational structure code
Verification rules: the organization code is the unique and invariable legal code identification of every organ, social group, enterprise and public institution in the whole country. The most recently used organizational code was enacted in 1997 and consists of an 8-digit (or capital Latin) ontology code and a 1-digit (or capital Latin) verification code. The ontology code adopts the sequential coding method of series (namely partition segment). The check code is calculated by the following formula: 8 C9 = 11 - MOD (∑Ci * Wi, 11)... (2) I =1 where: MOD -- stands for the complementary function; I -- indicates the sequence number of the code character from left to right; Ci -- represents the value of the code character in position I, using the characters listed in Appendix A "Code Character Set"; C9 -- checksum code; Wi: indicates the weighting factor of position I. Its value is as follows: I 1 2 3 4 5 6 7 8 Wi 3 7 9 10 5 8 4 2 When the MOD function is 1 (C9 = 10), the verification code is represented by the letter X. Verification method:Copy the code
checkOrgCodeValid: function(el){
var txtval = el.value;
var values=txtval.split("-");
var ws = [3.7.9.10.5.8.4.2];
var str = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var reg = /^([0-9A-Z]){8}$/;
if(! reg.test(values[0]) {return false
}
var sum = 0;
for (var i = 0; i < 8; i++) {
sum += str.indexOf(values[0].charAt(i)) * ws[i];
}
var C9 = 11 - (sum % 11);
var YC9 = values[1] +' ';
if (C9 == 11) {
C9 = '0';
} else if (C9 == 10) {
C9 = 'X' ;
} else {
C9 = C9+' ';
}
return YC9 == C9;
}
Copy the code
7. Verification of ID number
/** * verify id number *@param El Number Input *@returns {boolean}* /
function checkCardNo(el){
var txtval = el.value;
var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
return reg.test(txtval)
}
Copy the code
8. The js re adds HTTP identifiers to the URL
<! DOCTYPE html><html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script>
var html = 'http://www.google.com';
html += '\rwww.google.com';
html += '\rcode.google.com';
html += '\rhttp://code.google.com/hosting/search?q=label%3aPython';
var regex = /(https? : \ \ /)? (\w+\.?) +(\/[a-zA-Z0-9\?%=_\-\+\/]+)? /gi;
alert('before replace:');
alert(html);
html = html.replace(regex, function(match, capture) {
if (capture) {
return match
} else {
return 'http://'+ match; }}); alert('after replace:');
alert(html);
</script>
</head>
<body>
</body>
</html>
Copy the code
9. Verify URL validity
/** * VERIFY URL validity *@param str_url
* @returns {boolean}* /
function isURL(str_url) {/ / verification url
var strRegex = "^((https|http|ftp|rtsp|mms)? : / /)"
+ "? (([0-9a-z_!~*'().&=+$%-]+: )? [0-9a-z_!~*'().&=+$%-]+@)?" // The FTP user @ +"(([0-9] {1, 3} \.) {3} [0-9] {1, 3}" // IP urL-199.194.52.184
+ "|" // Allow IP and DOMAIN
+ "([0-9a-z_!~*'()-]+\.) *" // Domain name - WWW.
+ "([0-9 a-z] [0-9 a-z -], 21 {0})? [0-9a-z]\." // Secondary domain name
+ "[a-z] {2})" // first level domain- .com or .museum
+ "(: [0-9] {1, 4})?" // Port - :80
+ "((/?)|" // a slash isn't required if there is no file name
+ "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?) $";
var re = new RegExp(strRegex);
return re.test(str_url);
}
// Suggested re
functionisURL(str){
return!!!!! str.match(/(((^https? : (? : \ \ /)? (? :[-;:&=\+\$,\w]+@)? [A-Za-z0-9.-]+|(? :www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/g);
}
Copy the code
10. Customize jSONP methods
/** * Custom encapsulates jSONP methods *@param options* /
jsonp = function(options) {
options = options || {};
if(! options.url || ! options.callback) {throw new Error("Invalid parameter");
}
// Create a script tag and add it to the page
var callbackName = ('jsonp_' + Math.random()).replace("."."");
var oHead = document.getElementsByTagName('head') [0];
options.data[options.callback] = callbackName;
var params = formatParams(options.data);
var oS = document.createElement('script');
oHead.appendChild(oS);
// Create the jSONp callback function
window[callbackName] = function (json) {
oHead.removeChild(oS);
clearTimeout(oS.timer);
window[callbackName] = null;
options.success && options.success(json);
};
// Send the request
oS.src = options.url + '? ' + params;
// Timeout processing
if (options.time) {
oS.timer = setTimeout(function () {
window[callbackName] = null;
oHead.removeChild(oS);
options.fail && options.fail({ message: "Timeout"}); }, time); }};/** * Format parameters *@param data
* @returns {string}* /
formatParams = function(data) {
var arr = [];
for (var name in data) {
arr.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]));
}
return arr.join('&');
}
Copy the code
11. A cookie
/ / write cookies
setCookie = function(name,value,time) {
var strsec = getsec(time);
var exp = new Date(a); exp.setTime(exp.getTime() + strsec*1);
document.cookie = name + "="+ escape (value) + "; expires=" + exp.toGMTString();
}
// Cookie operator helper function
getsec = function(str){
var str1=str.substring(1,str.length)*1;
var str2=str.substring(0.1);
if (str2=="s") {return str1*1000;
}else if (str2=="h") {return str1*60*60*1000;
}else if (str2=="d") {return str1*24*60*60*1000; }}/ / read the cookies
getCookie = function(name) {
var arr,reg=new RegExp("(^| )"+name+"= (/ ^; (*). | $)");
if(arr=document.cookie.match(reg))
return (arr[2]);
else
return null;
}
/ / delete the cookies
delCookie = function(name) {
var exp = new Date(a); exp.setTime(exp.getTime() -1);
var cval = getCookie(name);
if(cval ! =null)
document.cookie= name + "="+cval+"; expires="+exp.toGMTString();
}
Copy the code
12. Generate random string (optionally length)
/** * Generates a random string (optionally of length) *@param len
* @returns {string}* /
randomString = function(len) {
len = len || 8;
var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; /**** removes confusing characters oOLl,9gq,Vv,Uu,I1****/ by default
var maxPos = $chars.length;
var pwd = ' ';
for (var i = 0; i < len; i++) {
pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
}
return pwd;
}
Copy the code
13. Browser judgment
function parseUA() {
var u = navigator.userAgent;
var u2 = navigator.userAgent.toLowerCase();
return { // Mobile terminal browser version information
trident: u.indexOf('Trident') > -1./ / IE kernel
presto: u.indexOf('Presto') > -1./ / opera kernel
webKit: u.indexOf('AppleWebKit') > -1.// Apple, Google kernel
gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') = = -1.// The Firefox kernel
mobile:!!!!! u.match(/AppleWebKit.*Mobile.*/), // Whether it is a mobile terminal
ios:!!!!! u.match(/\(i[^;] +; ( U;) ? CPU.+Mac OS X/), / / ios terminal
android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1.// An Android terminal or uc browser
iPhone: u.indexOf('iPhone') > -1.// Whether the browser is iPhone or QQHD
iPad: u.indexOf('iPad') > -1./ / whether the device
webApp: u.indexOf('Safari') = = -1.// Whether the web should be a program, without a header and a bottom
iosv: u.substr(u.indexOf('iPhone OS') + 9.3),
weixin: u2.match(/MicroMessenger/i) = ="micromessenger".ali: u.indexOf('AliApp') > -1}; }var ua = parseUA();
if(! ua.mobile) { location.href ='./pc.html';
}
Copy the code
14.Rem mobile adaptation
var rem = {
baseRem: 40.// Base size, according to iphone6 should be 20, here expanded twice, easy to calculate
baseWidth: 750.// The reference size is wide, here is according to the size of iHPONe6
rootEle: document.getElementsByTagName("html") [0].initHandle: function () {
this.setRemHandle();
this.resizeHandle();
},
setRemHandle: function () {
var clientWidth = document.documentElement.clientWidth || document.body.clientWidth;
this.rootEle.style.fontSize = clientWidth * this.baseRem / this.baseWidth + "px";
},
resizeHandle: function () {
var that = this;
window.addEventListener("resize".function () {
setTimeout(function () {
that.setRemHandle();
}, 300); }); }}; rem.initHandle();Copy the code
15. Obtain parameters after the URL
function GetRequest() {
var url = location.search; // Get the "?" in the url The string following the character
var theRequest = new Object(a);if(url.indexOf("?") != -1) {
var str = url.substr(1);
strs = str.split("&");
for(var i = 0; i < strs.length; i++) {
theRequest[strs[i].split("=") [0]] = (strs[i].split("=") [1]); }}return theRequest;
}
Copy the code
Dynamic loading of JS
function loadScript(url, callback) {
var script = document.createElement("script");
script.type = "text/javascript";
if(typeof(callback) ! ="undefined") {if (script.readyState) {
script.onreadystatechange = function () {
if (script.readyState == "loaded" || script.readyState == "complete") {
script.onreadystatechange = null; callback(); }}; }else {
script.onload = function () {
callback();
};
}
}
script.src = url;
document.body.appendChild(script);
}
Copy the code
17. Generate random color values
function getRandomColor () {
const rgb = []
for (let i = 0 ; i < 3; ++i){
let color = Math.floor(Math.random() * 256).toString(16);
color = color.length == 1 ? '0' + color : color;
rgb.push(color);
}
return The '#' + rgb.join(' ');
}
Copy the code
18. Event binding and unbinding
ElementClass.prototype.on = function (name, callback) {
this.callbacks[name] = this.callbacks[name] || []
this.callbacks[name].push(callback)
}
ElementClass.prototype.off = function (name, callback) {
var callbacks = this.callbacks[name]
if (callbacks && callbacks instanceof Array) {
var index = callbacks.indexOf(callback)
if(index ! = = -1) callbacks.splice(index, 1)
}
}
ElementClass.prototype.trigger = function (name, params) {
var callbacks = this.callbacks[name]
if (callbacks && callbacks instanceof Array) {
callbacks.forEach((cb) = > {
cb(params)
})
}
}
Copy the code
19. Audio playback on mobile terminal
/** * Mobile terminal H5 plays music processing, compatible with wechat terminal *@param El Music Audio element */
function playMusic(el) {
var b = document.getElementById(el);
var c = function c() {
b.play();
document.removeEventListener("touchstart", c, true);
};
b.play();
document.addEventListener("WeixinJSBridgeReady".function () {
c();
}, false);
document.addEventListener("YixinJSBridgeReady".function () {
c();
}, false);
document.addEventListener("touchstart", c, true);
}
Copy the code
20. Mobile video adaptation
<video class="video1" webkit-playsinline="true" x-webkit-airplay="true" playsinline="true" x5-video-player-type="h5" x5-video-player-fullscreen="true" preload="auto" poster="Poster image address" src="Video Address"></video>
Copy the code
21.Webpack+Vue-CLI implementation of automatic global registration components
// NPM import --save lodash
import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'
const requireComponent = require.context(
// The relative path of its component directory
'./components'.// Whether to query the subdirectory
false.// Match the regular expression of the underlying component filename to get the.vue ending file
/.vue$/
)
requireComponent.keys().forEach(fileName= > {
// Get the component configuration
const componentConfig = requireComponent(fileName)
// Get the PascalCase name of the component
const componentName = upperFirst(
camelCase(
// Strip the './ 'at the beginning of the file name and the extension at the end
fileName.replace(/^\.\/(.*)\.\w+$/.'$1')))// Globally register components
Vue.component(
componentName,
// If the component option is exported via 'export default',
// Then '.default 'is preferred,
// Otherwise fall back to the root of the use module.
componentConfig.default || componentConfig
)
Copy the code
22. Precision calculation
/** * addition operation, avoid data addition after the decimal point to produce multiple digits and loss of calculation accuracy. * *@param Num1 addend 1 | num2 number 2 * /
function numAdd (num1, num2) {
var baseNum, baseNum1, baseNum2;
try {
baseNum1 = num1.toString().split('. ') [1].length;
} catch (e) {
baseNum1 = 0;
}
try {
baseNum2 = num2.toString().split('. ') [1].length;
} catch (e) {
baseNum2 = 0;
}
baseNum = Math.pow(10.Math.max(baseNum1, baseNum2));
return (num1 * baseNum + num2 * baseNum) / baseNum;
}
/** * addition operation, avoid data subtraction after the decimal point to produce multiple digits and loss of calculation accuracy. * *@param Num1 minuend | num2 reduction * /
function numSub (num1, num2) {
var baseNum, baseNum1, baseNum2;
var precision; / / precision
try {
baseNum1 = num1.toString().split('. ') [1].length;
} catch (e) {
baseNum1 = 0;
}
try {
baseNum2 = num2.toString().split('. ') [1].length;
} catch (e) {
baseNum2 = 0;
}
baseNum = Math.pow(10.Math.max(baseNum1, baseNum2));
precision = (baseNum1 >= baseNum2) ? baseNum1 : baseNum2;
return ((num1 * baseNum - num2 * baseNum) / baseNum).toFixed(precision);
}
/** ** to avoid multiple digits and loss of calculation accuracy after multiplying data by decimal point. * *@param Num1 multiplicand | num2 multiplier * /
function numMulti (num1, num2) {
var baseNum = 0;
try {
baseNum += num1.toString().split('. ') [1].length;
} catch (e) {
console.error('numMulti error')}try {
baseNum += num2.toString().split('. ') [1].length;
} catch (e) {
console.error('numMulti error')}return Number(num1.toString().replace('. '.' ')) * Number(num2.toString().replace('. '.' ')) / Math.pow(10, baseNum);
}
/** * Division operation, avoid the data divided by the decimal point after the generation of multiple digits and calculation precision loss. * *@param Num1 dividend | num2 divisor * /
function numDiv (num1, num2) {
var baseNum1 = 0,
baseNum2 = 0;
var baseNum3, baseNum4;
try {
baseNum1 = num1.toString().split('. ') [1].length;
} catch (e) {
baseNum1 = 0;
}
try {
baseNum2 = num2.toString().split('. ') [1].length;
} catch (e) {
baseNum2 = 0;
}
baseNum3 = Number(num1.toString().replace('. '.' '));
baseNum4 = Number(num2.toString().replace('. '.' '));
return (baseNum3 / baseNum4) * Math.pow(10, baseNum2 - baseNum1);
}
Copy the code
23. Unified verification of social credit codes
Rules:
According to article 1 of article 4 of the Code Code Rules for unified Social Credit of Legal Persons and Other Organizations: Stipulate that the Common social credit code consists of 18 digits of Arabic numerals or capital English letters (not I, O, Z, S, V), It includes the first registration department code, the second organization type code, the third to the eighth administrative code of the registration authority, the ninth to the 17th main identification code (organization code), and the 18th check code. Part I (bit 1) : Registration authority code, indicated in Arabic numerals or English letters. For example, the establishment, civil affairs, and industry and commerce registration authorities use 1, 2, and 3 respectively, while other registration authorities can use corresponding Arabic numerals or English letters.
Part 2 (bit 2) : Organization type code, represented by Arabic numerals or English letters. The registration and administration department shall, according to its administrative functions, determine the classification codes of institutions registered in the department. For example, the establishment department can be 1 for government organs, 2 for public institutions, and 3 for mass organizations directly managed by the central organization office. Civil affairs departments can be 1 for social organizations, 2 for private non-enterprise units, and 3 for foundations. Industrial and commercial departments can be used 1 to represent enterprises, 2 to represent individual industrial and commercial households, 3 to represent farmer professional cooperatives.
Part III (digits 3-8) : the code of the administrative region of the registration authority, expressed in Arabic numerals. For example, the state with 100000, Beijing with 110000, registration by the system automatically generated, reflects the legal person and other organizations registration and registration of the location of the registration and management authorities, not only to meet the needs of the registration and management departments according to the region, but also to facilitate the society to the registration subject in the region for identification. (Refer to the Code for Administrative Divisions of the People’s Republic of China [GB/ T2260-2007])
Part 4 (bits 9-17) : The body identifier (organization code), which is represented by Arabic numerals or English letters. (Refer to The Code Compilation Rules of National Organizations [GB 11714 — 1997])
Part 5 (bit 18) : check code, represented by Arabic numerals or English letters.
/ * * *@description Verify the uniform Social Credit code *@param SocialCode Indicates the verified code *@return Boolean* /
function isSocialCode(socialCode) {
const reg = /[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}/;
return reg.test(socialCode);
}
Copy the code