首頁  >  文章  >  web前端  >  javascript常用函數和正規驗證表達式程式碼匯總

javascript常用函數和正規驗證表達式程式碼匯總

伊谢尔伦
伊谢尔伦原創
2017-07-20 10:13:421449瀏覽

常用正規驗證運算式

手機號碼驗證

var validate = function(num) {
var exp = /^1[3-9]\d{9}$/;
return exp.test(num);
};

身分證號驗證

var exp = /^[1-9]{1}[0-9]{14}$|^[1-9]{1}[0-9]{16}([0-9]|[xX])$/;

ip驗證

#
var exp = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;

常用js函數

$(window).scroll(function() {
var a = $(window).scrollTop();
if(a > 100) {
$('.go-top').fadeIn();
}else {
$('.go-top').fadeOut();
}
});
$(".go-top").click(function(){
$("html,body").animate({scrollTop:"0px"},'600');
});

阻止冒泡

#
function stopBubble(e){
e = e || window.event; 
if(e.stopPropagation){
e.stopPropagation(); //W3C阻止冒泡方法 
}else { 
e.cancelBubble = true; //IE阻止冒泡方法 
} 
}

全部取代replaceAll

var replaceAll = function(bigStr, str1, str2) { //把bigStr中的所有str1替换为str2
var reg = new RegExp(str1, 'gm');
return bigStr.replace(reg, str2);
}

取得瀏覽器url中的參數值

var getURLParam = function(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)', "ig").exec(location.search) || [, ""])[1].replace(/\+/g, '%20')) || null;
};

深度拷貝物件

function cloneObj(obj) {
var o = obj.constructor == Object ? new obj.constructor() : new obj.constructor(obj.valueOf());
for(var key in obj){
if(o[key] != obj[key] ){
if(typeof(obj[key]) == 'object' ){
o[key] = mods.cloneObj(obj[key]);
}else{
o[key] = obj[key];
}
}
}
return o;
}

陣列去重

var unique = function(arr) {
var result = [], json = {};
for (var i = 0, len = arr.length; i < len; i++){
if (!json[arr[i]]) {
json[arr[i]] = 1;
result.push(arr[i]); //返回没被删除的元素
}
}
return result;
};

判斷陣列元素是否重複

var isRepeat = function(arr) { //arr是否有重复元素
var hash = {};
for (var i in arr) {
if (hash[arr[i]]) return true;
hash[arr[i]] = true;
}
return false;
};

產生隨機數字

function randombetween(min, max){
return min + (Math.random() * (max-min +1));
}

作業cookie

own.setCookie = function(cname, cvalue, exdays){
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = &#39;expires=&#39;+d.toUTCString();
document.cookie = cname + &#39;=&#39; + cvalue + &#39;; &#39; + expires;
};
own.getCookie = function(cname) {
var name = cname + &#39;=&#39;;
var ca = document.cookie.split(&#39;;&#39;);
for(var i=0; i< ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == &#39; &#39;) c = c.substring(1);
if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
}
return &#39;&#39;;
};

以上是javascript常用函數和正規驗證表達式程式碼匯總的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn