cookie
var cookieUtil = {
get: function(name) {
var cookieName = encodeURIComponent(name) + "=",
cookieStart = document.cookie.indexOf(cookieName),
cookieValue = null;
if(cookieStart > -1) {
var cookieEnd = document.cookie.indexOf(';', cookieStart);
if(cookieEnd === -1) {
cookieEnd = document.cookie.length;
}
cookieValue = decodeURIComponent(document.cookie.substring(cookieStart+cookieName.length, cookieEnd));
}
return cookieValue;
},
set: function(name, value, expires, domain, path, secure) {
var cookieText = encodeURIComponent(name)+'='+encodeURIComponent(value);
if(expires instanceof Date) {
cookieText += '; expires=' + expires.toGMTString();
} else if(typeof expires === 'number') {
cookieText += '; expires=' + (new Date(expires*24*60*60*1000+Date.now())).toGMTString();
}
// (new Date(毫秒数)).toGMTString()
// 多少天后 (new Date(expires*24*60*60*1000+Date.now())).toGMTString()
if(domain) { cookieText += '; domain=' + domain; }
if(path) { cookieText += '; path=' + path; }
if(secure) { cookieText += '; secure'; }
document.cookie = cookieText;
},
unset: function(name, domain, path, secure) { this.set(name, '', new Date(0), path, domain, secure); }
}
name: cookie唯一的名称 cookie必须经过URL编码 不区分大小写 实践中最好当作cookie区分大小写
value: 字符串值 必须经过URL编码
expires: 失效时间 cookie何时被删除的时间戳 默认情况下会话结束立即将所有cookie删除
path: 域 所有向该域的请求中都会包含cookie 可以包含子域名 也可以不包含
domain: 路径 对于指定域中的那个路径 应该向服务器发送cookie
secure: 安全标志 指定后,cookie只有在使用SSL连接时才会发送到服务器 是cookie中唯一一个非名值对的,直接包含secure
JS -- 正则
手机号码
/^1(3[0-9]|4[57]|5[0-35-9]|7[0135678]|8[0-9])\d{8}$/
电子邮箱
/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/ /^[a-z\d]+(\.[a-z\d]+)*@([\da-z](-[\da-z])?)+(\.{1,2}[a-z]+)+$/
删除 emoji 表情
str.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,'');
- 验证车牌
var re=/^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领]{1}[A-HJ-NP-Z]{1}[[A-HJ-NP-Z0-9]{5}$/; //[A-HJ-NP-Z0-9挂学警港澳]{1}
JS -- 上传图片 预览图片
/*#file{width:0;height:0}*/
.imgs{width:200px;height:200px}
<label>
<input type="file" name="myfile" id="file" multiple="multiple" min="1" max="3" accept="image/png, image/jpg, image/jpeg" />
<span>点击选择文件</span>
</label>
<div class="imgWrap">
<!--<img class="imgs" src="" alt="预览图片alt" title="预览图片title">-->
</div>
<script src="../jquery-2.1.4.min.js"></script>
//点击选择图片
$('#file').on('change',function(e){
// createObjectURL 预览图片
// 上传同一个文件,不会触发change事件,即便该文件作过修改
// 用户若是在上传过程当中点击了“取消”,已经上传的文件会被移除
//this.files可以获取多张 this.files[0].name-文件名 .size-文件大小(Byte) .type-文件类型 .value
let newSrc = getObjectURL(this.files[0]);
// document.getElementById('imgs').src=newSrc;
// $('.imgs').eq(0).attr('src',newSrc);//'https://static.clewm.net/cli/images/cli_logo_new.png'
let imgHtml='<img class="imgs" alt="预览图片alt" title="预览图片title" src="'+newSrc+'">'
// <img class="imgs" src="" alt="预览图片alt" title="预览图片title">
$('.imgWrap').append(imgHtml);
//FileReader 预览图片
/* let reads= new FileReader();
let img=this.files[0];
reads.readAsDataURL(img);
reads.onload=function (e) {
// document.getElementsByClassName('imgs')[0].src=this.result;
$('.imgs').attr('src',reads.result);//this.result e.target.result e.currentTarget.result
};*/
});
//建立一個可存取到該file的url
function getObjectURL(file) {
let url = null ;
// 下面函数执行的效果是一样的,只是需要针对不同的浏览器执行不同的 js 函数而已
if (window.createObjectURL) { // basic window.createObjectURL!=undefined
url = window.createObjectURL(file) ;
} else if (window.webkitURL) { // webkit or chrome
url = window.webkitURL.createObjectURL(file) ;
} else if (window.URL) { // mozilla(firefox)
url = window.URL.createObjectURL(file) ;
}
return url ;
}
//上传
$("#sub").click(function() {
const files=$("#file")[0].files[0];//this.files可以获取多张
var formData=new FormData();
formData.append('myfile',files);
$.ajax({
url: '/uploadimg',
method: 'POST',
processData:false,// tell jQuery not to process the data 默认情况下jquery会对数据做处理
contentType:false, // tell jQuery not to set contentType
dataType:'JSON',
data: formData,
success: function (e) {
console.log(e);
},
fail: function (err) {
console.error(err);
}
});
});
通信
1、移动端打电话
window.location.href = ("tel:" + phone);
2、移动端发送短信--Android、iOS
var u = navigator.userAgent, app = navigator.appVersion;
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; // android终端或者uc浏览器
var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
//sms:10086?body=1008611 sms:10086&body=1008611
if(isAndroid == true) {
window.location.href=("sms:10694006929598?body="+text);
} else if(isiOS == true) {
window.location.href=("sms:10694006929598&body="+text);
}
获取用户地理位置
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
}
else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " +
position.coords.latitude +
"<br />Longitude: " +
position.coords.longitude;
}
function showError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
错误代码:
-Permission denied - 用户不允许地理定位
-Position unavailable - 无法获取当前位置
-Timeout - 操作超时
-Unknown error - 未知错误
实现数组迭代方法
1、实现arr.forEach() IE8及以下不支持原生 Array.prototype.forEach
if (!Array.prototype.forEach) {
Array.prototype.forEach = function(callback, thisArg) {
var T, k;
if (this == null) {
throw new TypeError('this is null or not defined');
}
var O = Object(this);
var len = O.length >>> 0;
// 所有非数值转换成0;所有大于等于 0 等数取整数部分
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
if (arguments.length > 1) {
T = thisArg;
}
k = 0;
while (k < len) {
var kValue;
if (k in O) {
kValue = O[k];
callback.call(T, kValue, k, O);
}
k++;
}
};
}
2、实现arr.filter() filter
if (!Array.prototype.filter){
Array.prototype.filter = function(func, thisArg) {
'use strict';
if ( ! ((typeof func === 'Function' || typeof func === 'function') && this) )
throw new TypeError();
var len = this.length >>> 0,
res = new Array(len), // preallocate array
t = this, c = 0, i = -1;
if (thisArg === undefined){
while (++i !== len){
// checks to see if the key was set
if (i in this){
if (func(t[i], i, t)){
res[c++] = t[i];
}
}
}
}
else{
while (++i !== len){
// checks to see if the key was set
if (i in this){
if (func.call(thisArg, t[i], i, t)){
res[c++] = t[i];
}
}
}
}
res.length = c; // shrink down array to proper size
return res;
};
}
数组去重
Array.prototype.unique_filterArray = Array.prototype.unique_filterArray || function(){
return this.filter(function(item, index, arr){
return arr.indexOf(item) === index;
});
}
Array.prototype.unique = function(){
var res = [];
var json = {};
for(var i = 0; i < this.length; i++){
if(!json[this[i]]){
res.push(this[i]);
json[this[i]] = 1;
}
}
return res;
};
arr.unique();//调用 Array.prototype.unique
Array.prototype.remove = function(val) {
var index = this.indexOf(val);
if (index > -1) {
this.splice(index, 1);
}
};
使用JQ删除某一项 -- arr.splice($.inArray(item,arr),1);
解析URI参数
- *将GET参数按照键值对的形式输出json
function getUrl(str) {
var data1=str.split("?")[1];
var result={};
if(data1.indexOf("&") > -1) {
var bigArr=data1.split("&");
for(var a=0,b=bigArr.length;a<b;a++) {
var smallArr=bigArr[a].split("=");
result[smallArr[0]]=smallArr[1];
}
} else {
var arr1=data1.split("=");
result[arr1[0]]=arr1[1];
}
console.log(result);
return result;
}
// getUrl("https://www.baidu.com/s?ie=utf-8&a=1&b=2&c=3&d");//{ie: "utf-8",a: "1", b: "2", c: "3", d: undefined}
- 解析单个参数
function getQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
if (r != null) return unescape(r[2]); return null;
}
http://10.108.105.176:666/bindSuccess/coupons.html?values=uri1&gets=uri2&types=uri3
var values=getQueryString("values") ||300,
gets=getQueryString("gets"),
types=getQueryString("types");
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。