100个原生javascript代码片段知识点详细汇总【实践】-ag凯发k8国际

作者:小棋子js

转发链接:https://www.jianshu.com/p/b5171efa340f

javascript 是目前最流行的编程语言之一,正如大多数人所说:“如果你想学一门编程语言,请学javascript。”

freecodecamp的创始人 quincy larson 在最近的一次采访中被问到哪种语言开发人员应该首先学习。他回答:“ javascript。”:

“软件正在吞噬世界,javascript正在吞噬软件。javascript每年都在变得越来越占主导地位,而且没人知道最终会取代它的是什么。" 如果您没有充分的理由学习一种新语言(例如您的工作要求您维护非javascript代码库),那么我的建议是着重于提高javascript的水平。”

听我说这么多,你是不是很激动呢。这里有100端常用的js代码片段,方便你学习和使用。

前面小编也整理一部分关于javascript相关学习资料文章,不知道小伙伴们是否还记得:

《》

《》

《》

《》

《》

《》

《》

更多javascript相关学习资料文章,请见文章底部

function cutstr(str, len) { var temp; var icount = 0; var patrn = /[^x00-xff]/; // 匹配双字节字符(包括汉字在内) var strren = ""; for (var i = 0; i < str.length; i ) { if (icount < len - 1) { temp = str.substr(i, 1); if (patrn.exec(temp) == null) { icount = icount 1; } else { icount = icount 2; } } else { break; } } return strre "...";}

function gethost(url) { var host = "null"; if (typeof url == undefined || url === null) { url = window.location.href; } var regex = /^w ://([^/]*).*/; var match = url.match(regex); if (typeof match != undefined && match != null) { host = match[1]; } return host;}

string.prototype.trim = function() { var reextraspace = /^s*(.*?)s $/; return this.replace(reextraspace, "$1");}

string.prototype.replaceall = function(s1, s2) { return this.replace(new regexp(s1, "gm"), s2);}

function htmlencode(text) { return text.replace(/&/g, '&') .replace(/"/g, '"') .replace(//g, '>');}

function htmldecode(text) { return text.replace('&', /&/g) .replace('"', /"/g) .replace('<', /', />/g);}

date.prototype.format = function(formatstr) { var str = formatstr; var week = ['日', '一', '二', '三', '四', '五', '六']; str = str.replace(/yyyy|yyyy/, this.getfullyear()); str = str.replace(/yy|yy/, (this.getyear() % 100) > 9 ? (this.getyear() % 100).tostring() : '0' (this.getyear() % 100)); str = str.replace(/mm/, (this.getmonth() 1) > 9 ? (this.getmonth() 1).tostring() : '0' (this.getmonth() 1)); str = str.replace(/m/g, (this.getmonth() 1)); str = str.replace(/w|w/g, week[this.getday()]); str = str.replace(/dd|dd/, this.getdate() > 9 ? this.getdate().tostring() : '0' this.getdate()); str = str.replace(/d|d/g, this.getdate()); str = str.replace(/hh|hh/, this.gethours() > 9 ? this.gethours().tostring() : '0' this.gethours()); str = str.replace(/h|h/g, this.gethours()); str = str.replace(/mm/, this.getminutes() > 9 ? this.getminutes().tostring() : '0' this.getminutes()); str = str.replace(/m/g, this.getminutes()); str = str.replace(/ss|ss/, this.getseconds() > 9 ? this.getseconds().tostring() : '0' this.getseconds()); str = str.replace(/s|s/g, this.getseconds()); return str }

function isdigit(value) { var patrn = /^[0-9]*$/; if (patrn.exec(value) == null || value == "") { return false } else { return true }}

function setcookie(name, value, hours) { var d = new date(); var offset = 8; var utc = d.gettime() (d.gettimezoneoffset() * 60000); var nd = utc (3600000 * offset); var exp = new date(nd); exp.settime(exp.gettime() hours * 60 * 60 * 1000); document.cookie = name "=" escape(value) ";path=/;expires=" exp.togmtstring() ";domain=360doc.com;"}

function getcookie(name) { var arr = document.cookie.match(new regexp("(^| )" name "=([^;]*)(;|$)")); if (arr != null) return unescape(arr[2]); return null}

function addfavorite(surl, stitle) { try { window.external.addfavorite(surl, stitle) } catch(e) { try { window.sidebar.addpanel(stitle, surl, "") } catch(e) { alert("加入收藏失败,请使用ctrl d进行添加") } }}

function sethomepage() { if (document.all) { document.body.style.behavior = 'url(/57042.html)'; document.body.sethomepage('http://***'); } else if (window.sidebar) { if (window.netscape) { try { netscape.security.privilegemanager.enableprivilege("universalxpconnect") } catch(e) { alert("该操作被浏览器拒绝,如果想启用该功能,请在地址栏内输入 about:config,然后将项 signed.applets.codebase_principal_support 值该为true") } } var prefs = components.classes['@mozilla.org/preferences-service;1'].getservice(components.interfaces.nsiprefbranch); prefs.setcharpref('browser.startup.homepage', 'http://***') }}

var ua = navigator.useragent.tolowercase();var isie6 = ua.indexof("msie 6") > -1;if (isie6) { try { document.execcommand("backgroundimagecache", false, true) } catch(e) {}}

function loadstyle(url) { try { document.createstylesheet(url) } catch(e) { var csslink = document.createelement('link'); csslink.rel = 'stylesheet'; csslink.type = 'text/css'; csslink.href = url; var head = document.getelementsbytagname('head')[0]; head.appendchild(csslink) }}

function evalscript(s) { if(s.indexof(']*?>([^x00]*?)/ig; var arr = []; while(arr = p.exec(s)) { var p1 = /]*?src="([^>]*?)"[^>]*?(reload="1")?(?:charset="([w-] ?)")?>/i; var arr1 = []; arr1 = p1.exec(arr[0]); if(arr1) { appendscript(arr1[1], '', arr1[2], arr1[3]); } else { p1 = /([^x00] ?)/i; arr1 = p1.exec(arr[0]); appendscript('', arr1[2], arr1[1].indexof('reload=') != -1); } } return s;}

function stripscript(s) { return s.replace(/.*?/ig, '');}

function appendscript(src, text, reload, charset) { var id = hash(src text); if(!reload && in_array(id, evalscripts)) return; if(reload && $(id)) { $(id).parentnode.removechild($(id)); } evalscripts.push(id); var scriptnode = document.createelement("script"); scriptnode.type = "text/javascript"; scriptnode.id = id; scriptnode.charset = charset ? charset : (browser.firefox ? document.characterset : document.charset); try { if(src) { scriptnode.src = src; scriptnode.onloaddone = false; scriptnode.onload = function () { scriptnode.onloaddone = true; jsloaded[src] = 1; }; scriptnode.onreadystatechange = function () { if((scriptnode.readystate == 'loaded' || scriptnode.readystate == 'complete') && !scriptnode.onloaddone) { scriptnode.onloaddone = true; jsloaded[src] = 1; } }; } else if(text){ scriptnode.text = text; } document.getelementsbytagname('head')[0].appendchild(scriptnode); } catch(e) {}}

function $(id) { return !id ? null : document.getelementbyid(id);}

function browserversion(types) { var other = 1; for(i in types) { var v = types[i] ? types[i] : i; if(useragent.indexof(v) != -1) { var re = new regexp(v '(/|s)([d.] )', 'ig'); var matches = re.exec(useragent); var ver = matches != null ? matches[2] : 0; other = ver !== 0 && v != 'mozilla' ? 0 : other; }else { var ver = 0; } eval('browser.' i '= ver'); } browser.other = other;}

function $(id) { return !id ? null : document.getelementbyid(id);}function display(id) { var obj = $(id); if(obj.style.visibility) { obj.style.visibility = obj.style.visibility == 'visible' ? 'hidden' : 'visible'; } else { obj.style.display = obj.style.display == '' ? 'none' : ''; }}

function insertafter(newchild, refchild) { var parelem = refchild.parentnode; if(parelem.lastchild == refchild){ refchild.appendchild(newchild); }else{ parelem.insertbefore(newchild, refchild.nextsibling); } }

function addeventsamp(obj, evt, fn){ if (obj.addeventlistener) { obj.addeventlistener(evt, fn, false); }else if(obj.attachevent){ obj.attachevent('on' evt, fn); } }

function focuslast(){ var e = event.srcelement; var r =e.createtextrange(); r.movestart('character',e.value.length); r.collapse(true); r.select(); }

function geturlstate(url) { var xmlhttp = new activexobject("microsoft.xmlhttp"); xmlhttp.open("get", url, false); try { xmlhttp.send(); } catch(e) { } finally { var result = xmlhttp.responsetext; if(result) { if(xmlhttp.status==200){ return true; }else{ return false; } } else { return false; } } }

function formatcss(s){ //格式化代码 s = s.replace(/s*([{}:;,])s*/g, "$1"); s = s.replace(/;s*;/g, ";"); //清除连续分号 s = s.replace(/,[s.#d]*{/g, "{"); s = s.replace(/([^s]){([^s])/g, "$1 {nt$2"); s = s.replace(/([^s])}([^n]*)/g, "$1n}n$2"); s = s.replace(/([^s]);([^s}])/g, "$1;nt$2"); return s;}

function yasuocss (s) { //压缩代码 s = s.replace(//*(.|n)*?*//g, ""); //删除注释 s = s.replace(/s*([{}:;,])s*/g, "$1"); s = s.replace(/,[s.#d]*{/g, "{"); //容错处理 s = s.replace(/;s*;/g, ";"); //清除连续分号 s = s.match(/^s*(s (s s )*)s*$/); //去掉首尾空白 return (s == null) ? "" : s[1];}

var currentpageurl = "";if (typeof this.href === undefined) { currentpageurl = document.location.tostring().tolowercase();}else { currentpageurl = this.href.tostring().tolowercase();}

function _ip2int(ip){ var num = 0; ip = ip.split("."); num = number(ip[0]) * 256 * 256 * 256 number(ip[1]) * 256 * 256 number(ip[2]) * 256 number(ip[3]); num = num >>> 0; return num;}

function _int2ip(num){ var str; var tt = new array(); tt[0] = (num >>> 24) >>> 0; tt[1] = ((num << 8) >>> 24) >>> 0; tt[2] = (num << 16) >>> 24; tt[3] = (num << 24) >>> 24; str = string(tt[0]) "." string(tt[1]) "." string(tt[2]) "." string(tt[3]); return str;}

function checkall() { var selectall = document.getelementbyid("selectall"); var allbox = document.getelementsbyname("allbox"); if (selectall.checked) { for (var i = 0; i < allbox.length; i ) { allbox[i].checked = true; } } else { for (var i = 0; i < allbox.length; i ) { allbox[i].checked = false; } }}

function ismobile(){ if (typeof this._ismobile === 'boolean'){ return this._ismobile; } var screenwidth = this.getscreenwidth(); var fixviewportsexperiment = renderermodel.runningexperiments.fixviewport || renderermodel.runningexperiments.fixviewport; var fixviewportsexperimentrunning = fixviewportsexperiment && (fixviewportsexperiment.tolowercase() === "new"); if(!fixviewportsexperiment){ if(!this.isapplemobiledevice()){ screenwidth = screenwidth/window.devicepixelratio; } } var ismobilescreensize = screenwidth < 600; var ismobileuseragent = false; this._ismobile = ismobilescreensize && this.istouchscreen(); return this._ismobile;}

function ismobileuseragent() { return (/iphone|ipod|android.*mobile|windows.*phone|blackberry.*mobile/i.test(window.navigator.useragent.tolowercase()));}

function isapplemobiledevice() { return (/iphone|ipod|ipad|macintosh/i.test(navigator.useragent.tolowercase()));}

function isandroidmobiledevice(){ return (/android/i.test(navigator.useragent.tolowercase()));}

function istouchscreen() { return (('ontouchstart' in window) || window.documenttouch && document instanceof documenttouch);}

function isnewchromeonandroid(){ if(this.isandroidmobiledevice()){ var useragent = navigator.useragent.tolowercase(); if((/chrome/i.test(useragent))){ var parts = useragent.split('chrome/'); var fullversionstring = parts[1].split(" ")[0]; var versionstring = fullversionstring.split('.')[0]; var version = parseint(versionstring); if(version >= 27){ return true; } } } return false;}

function isviewportopen() { return !!document.getelementbyid('wixmobileviewport');}

function getinitzoom() { if(!this._initzoom) { var screenwidth = math.min(screen.height, screen.width); if(this.isandroidmobiledevice() && !this.isnewchromeonandroid()) { screenwidth = screenwidth / window.devicepixelratio; } this._initzoom = screenwidth /document.body.offsetwidth; } return this._initzoom;}

function getzoom(){ var screenwidth = (math.abs(window.orientation) === 90) ? math.max(screen.height, screen.width) : math.min(screen.height, screen.width); if(this.isandroidmobiledevice() && !this.isnewchromeonandroid()){ screenwidth = screenwidth/window.devicepixelratio; } var fixviewportsexperiment = renderermodel.runningexperiments.fixviewport || renderermodel.runningexperiments.fixviewport; var fixviewportsexperimentrunning = fixviewportsexperiment && (fixviewportsexperiment === "new" || fixviewportsexperiment === "new"); if(fixviewportsexperimentrunning){ return screenwidth / window.innerwidth; }else{ return screenwidth / document.body.offsetwidth; }}

function getscreenwidth(){ var smallerside = math.min(screen.width, screen.height); var fixviewportsexperiment = renderermodel.runningexperiments.fixviewport || renderermodel.runningexperiments.fixviewport; var fixviewportsexperimentrunning = fixviewportsexperiment && (fixviewportsexperiment.tolowercase() === "new"); if(fixviewportsexperiment){ if(this.isandroidmobiledevice() && !this.isnewchromeonandroid()){ smallerside = smallerside/window.devicepixelratio; } } return smallerside;}

function is { var regular = /^b(((https?|ftp)://)?[-a-z0-9] (.[-a-z0-9] )*.(?:com|edu|gov|int|mil|net|org|biz|info|name|museum|asia|coop|aero|[a-z][a-z]|((25[0-5])|(2[0-4]d)|(1dd)|([1-9]d)|d))b(/[-a-z0-9_:@&?= ,.!/~%$]*)?)$/i if (regular.test(strurl)) { return true; } else { return false; }}

function getelementsbyclassname(name) { var tags = document.getelementsbytagname('*') || document.all; var els = []; for (var i = 0; i < tags.length; i ) { if (tags[i].classname) { var cs = tags[i].classname.split(' '); for (var j = 0; j < cs.length; j ) { if (name == cs[j]) { els.push(tags[i]); break; } } } } return els;}

string.prototype.startwith = function (s) { return this.indexof(s) == 0;}

string.prototype.endwith = function (s) { var d = this.length - s.length; return (d >= 0 && this.lastindexof(s) == d);}

function getie(){ if (window.activexobject){ var v = navigator.useragent.match(/msie ([^;] )/)[1]; return parsefloat(v.substring(0, v.indexof("."))); } return false;}

function getpageheight() { var g = document, a = g.body, f = g.documentelement, d = g.compatmode == "backcompat" ? a : g.documentelement; return math.max(f.scrollheight, a.scrollheight, d.clientheight);}

function getpagescrollleft(){ var a = document; return a.documentelement.scrollleft || a.body.scrollleft;}

function getpageviewwidth(){ var d = document, a = d.compatmode == "backcompat" ? d.body : d.documentelement; return a.clientwidth; // 可视宽度为clientwidth}

// 考虑带滚动条的全部宽度function getpagewidth(){ var g = document, a = g.body, f = g.documentelement, d = g.compatmode == "backcompat" ? a : g.documentelement; return math.max(f.scrollwidth, a.scrollwidth, d.clientwidth);}

function getpagescrolltop(){ var a = document; return a.documentelement.scrolltop || a.body.scrolltop;}

function getpageviewheight() { var d = document, a = d.compatmode == "backcompat" ? d.body : d.documentelement; return a.clientheight;}

function addevt(otarget, sevttype, fnhandle) { if(!otarget) {return;} if(otarget.addeventlistener) { otarget.addeventlistener(sevttype, fnhandle, false); } else if(otarget.attachevent) { otarget.attachevent("on" sevttype, fnhandle); } else { otarget["on" sevttype] = fnhandle; }}

function delevt(otarget, sevttype, fnhandle){ if(!otarget) {return;} if(otarget.addeventlistener) { otarget.addeventlistener(sevttype,fnhandle,false); } else if(otarget.attachevent) { otarget.attachevent("on" sevttype,fnhandle); } else { otarget["on" sevttype] = fnhandle; }}

function removeurlprefix(a) { a = a.replace(/:/g,":").replace(/./g,".").replace(///g,"/"); while(trim(a).tolowercase().indexof("http://") == 0) { a = trim(a.replace(/http:///i,"")); } return a;}

function uniqueid() { var a = math.random, b = parseint; return number(new date()).tostring() b(10*a()) b(10*a()) b(10*a());}

function chgcase(sstr,icase){ if(typeof sstr != "string" || sstr.length <= 0 || !(icase === 0 || icase == 1)){ return sstr; } var i,ors=[],icode; if(icase){/*半->全*/ for(i=0; i半*/ for(i=0; i 65280 && icode < 65375){ icode -= 65248; } ors.push(string.fromcharcode(icode)); } } return ors.join(""); }

function checkkey(ikey){ if(ikey == 32 || ikey == 229){return true;} /*空格和异常*/ if(ikey>47 && ikey < 58){return true;} /*数字*/ if(ikey>64 && ikey < 91){return true;} /*字母*/ if(ikey>95 && ikey < 108){return true;} /*数字键盘1*/ if(ikey>108 && ikey < 112){return true;} /*数字键盘2*/ if(ikey>185 && ikey < 193){return true;} /*符号1*/ if(ikey>218 && ikey < 223){return true;} /*符号2*/ return false;}

function getscrollxy() { return document.body.scrolltop ? { x: document.body.scrollleft, y: document.body.scrolltop }: { x: document.documentelement.scrollleft, y: document.documentelement.scrolltop }}

date.prototype.format = function(format) { // author: meizz var o = { "m " : this.getmonth() 1, // month "d " : this.getdate(), // day "h " : this.gethours(), // hour "m " : this.getminutes(), // minute "s " : this.getseconds(), // second "q " : math.floor((this.getmonth() 3) / 3), // quarter "s" : this.getmilliseconds() // millisecond } if(/(y )/.test(format)) { format=format.replace(regexp.$1, (this.getfullyear() "").substr(4 - regexp.$1.length)); } for(var k in o)if(new regexp("(" k ")").test(format)) { format = format.replace(regexp.$1, regexp.$1.length==1 ? o[k] : ("00" o[k]).substr(("" o[k]).length)); } return format;}alert(new date().format("yyyy-mm-dd hh:mm:ss"));

/*1、< 60s, 显示为“刚刚”2、>= 1min && < 60 min, 显示与当前时间差“xx分钟前”3、>= 60min && < 1day, 显示与当前时间差“今天 xx:xx”4、>= 1day && < 1year, 显示日期“xx月xx日 xx:xx”5、>= 1year, 显示具体日期“xxxx年xx月xx日 xx:xx” */function timeformat(time){ var date = new date(time) , curdate = new date() , year = date.getfullyear() , month = date.getmonth() 1 , day = date.getdate() , hour = date.gethours() , minute = date.getminutes() , curyear = curdate.getfullyear() , curhour = curdate.gethours() , timestr; if(year < curyear){ timestr = year '年' month '月' day '日 ' hour ':' minute; }else{ var pasttime = curdate - date , pasth = pasttime/3600000; if(pasth > curhour){ timestr = month '月' day '日 ' hour ':' minute; }else if(pasth >= 1){ timestr = '今天 ' hour ':' minute '分'; }else{ var pastm = curdate.getminutes() - minute; if(pastm > 1){ timestr = pastm '分钟前'; }else{ timestr = '刚刚'; } } } return timestr;}

// 针对火狐不支持offsetx/yfunction getoffset(e) { var target = e.target, // 当前触发的目标对象 eventcoord, pagecoord, offsetcoord; // 计算当前触发元素到文档的距离 pagecoord = getpagecoord(target); // 计算光标到文档的距离 eventcoord = { x : window.pagexoffset e.clientx, y : window.pageyoffset e.clienty }; // 相减获取光标到第一个定位的父元素的坐标 offsetcoord = { x : eventcoord.x - pagecoord.x, y : eventcoord.y - pagecoord.y }; return offsetcoord;}function getpagecoord(element) { var coord = { x : 0, y : 0 }; // 计算从当前触发元素到根节点为止, // 各级 offsetparent 元素的 offsetleft 或 offsettop 值之和 while (element){ coord.x = element.offsetleft; coord.y = element.offsettop; element = element.offsetparent; } return coord;}

//正整数/^[0-9]*[1-9][0-9]*$/;//负整数/^-[0-9]*[1-9][0-9]*$/;//正浮点数/^(([0-9] .[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*.[0-9] )|([0-9]*[1-9][0-9]*))$/; //负浮点数/^(-(([0-9] .[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*.[0-9] )|([0-9]*[1-9][0-9]*)))$/; //浮点数/^(-?d )(.d )?$/;//email地址/^[w-] (.[w-] )*@[w-] (.[w-] ) $/;//url地址/^[a-za-z] ://(w (-w )*)(.(w (-w )*))*(?s*)?$/;//年/月/日(年-月-日、年.月.日)/^(19|20)dd[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$/;//匹配中文字符/[u4e00-u9fa5]/;//匹配帐号是否合法(字母开头,允许5-10字节,允许字母数字下划线)/^[a-za-z][a-za-z0-9_]{4,9}$/;//匹配空白行的正则表达式/ns*r/;//匹配中国邮政编码/[1-9]d{5}(?!d)/;//匹配身份证/d{15}|d{18}/;//匹配国内电话号码/(d{3}-|d{4}-)?(d{8}|d{7})?/;//匹配ip地址/((2[0-4]d|25[0-5]|[01]?dd?).){3}(2[0-4]d|25[0-5]|[01]?dd?)/;//匹配首尾空白字符的正则表达式/^s*|s*$/;//匹配html标记的正则表达式< (s*?)[^>]*>.*?|< .*? />;

function backtop(btnid) { var btn = document.getelementbyid(btnid); var d = document.documentelement; var b = document.body; window.onscroll = set; btn.style.display = "none"; btn.onclick = function() { btn.style.display = "none"; window.onscroll = null; this.timer = setinterval(function() { d.scrolltop -= math.ceil((d.scrolltop b.scrolltop) * 0.1); b.scrolltop -= math.ceil((d.scrolltop b.scrolltop) * 0.1); if ((d.scrolltop b.scrolltop) == 0) clearinterval(btn.timer, window.onscroll = set); }, 10); }; function set() { btn.style.display = (d.scrolltop b.scrolltop > 100) ? 'block': "none"; }};backtop('gotop');

// 用法:如果地址是 test.htm?t1=1&t2=2&t3=3, 那么能取得:get["t1"], get["t2"], get["t3"]function get_get() { querystr = window.location.href.split("?"); if(querystr[1]) { var gets = querystr[1].split("&"), get = new array(); for(i = 0; i < gets.length; i ){ tmp_arr = gets[i].split("="); key = tmp_arr[0]; get[key] = tmp_arr[1]; } } return querystr[1];}

function checkall(form, prefix, checkall) { var checkall = checkall ? checkall : 'chkall'; for(var i = 0; i < form.elements.length; i ) { var e = form.elements[i]; if(e.type=="checkbox"){ e.checked = form.elements[checkall].checked; } }}

function uncheckall(form) { for (var i = 0; i < form.elements.length; i ){ var e = form.elements[i]; if (e.name != 'chkall') e.checked = !e.checked; }}

function openwindow(url,windowname,width,height){ var x = parseint(screen.width / 2.0) - (width / 2.0); var y = parseint(screen.height / 2.0) - (height / 2.0); var ismsie= (navigator.appname == "microsoft internet explorer"); if (ismsie) { var p = "resizable=1,location=no,scrollbars=no,width="; p = p width; p = p ",height="; p = p height; p = p ",left="; p = p x; p = p ",top="; p = p y; retval = window.open(url, windowname, p); } else { var win = window.open(url, "zyiispopup", "top=" y ",left=" x ",scrollbars=" scrollbars ",dialog=yes,modal=yes,width=" width ",height=" height ",resizable=no" ); eval("try { win.resizeto(width, height); } catch(e) { }"); win.focus(); }}

function client(o){ var b = navigator.useragent.tolowercase(); var t = false; if (o == 'isop'){ t = b.indexof('opera') > -1; } if (o == 'isie'){ t = b.indexof('msie') > -1; } if (o == 'isff'){ t = b.indexof('firefox') > -1; } return t;}

function get_radio_value(field){ if(field && field.length){ for(var i = 0; i < field.length; i ){ if(field[i].checked){ return field[i].value; } } }else { return; } }

function get_checkbox_value(field) { if(field && field.length){ for(var i = 0; i < field.length; i ){ if(field[i].checked && !field[i].disabled){ return field[i].value; } } } else { return; } }

function isemail(str){ var re=/^w ((-w )|(.w ))*@[a-za-z0-9] ((.|-)[a-za-z0-9] )*.[a-za-z0-9] $/; if (re.test(str) != true) { return false; }else{ return true; } }

function isvalidreg(chars){ var re=/<|>|[|]|{|}|『|』|※||||§|||||||□||㊣|﹋|⊕|⊙|〒|ㄅ|ㄆ|ㄇ|ㄈ|ㄉ|ㄊ|ㄋ|ㄌ|ㄍ|ㄎ|ㄏ|ㄐ|ㄑ|ㄒ|ㄓ|ㄔ|ㄕ|ㄖ|ㄗ|ㄘ|ㄙ|ㄚ|ㄛ|ㄜ|ㄝ|ㄞ|ㄟ|ㄢ|ㄣ|ㄤ|ㄥ|ㄦ|ㄧ|ㄨ|ㄩ|■|▄|▆|*|@|#|^|/; if (re.test( chars) == true) { return false; }else{ return true; } }

function isvalidlength(chars, len) { if (chars.length < len) { return false; } return true;}

function isvalid { var re=/^([hh][tt]{2}[pp]://|[hh][tt]{2}[pp][ss]://)(s .s )$/; if (!isnull(chars)) { chars = jstrim(chars); if (chars.match(re) == null) return false; else return true; } return false;}

function isvaliddecimal( chars ) { var re=/^d*.?d{1,2}$/; if (chars.match(re) == null) return false; else return true;}

function isnumber(chars) { var re=/^d*$/; if (chars.match(re) == null) return false; else return true;}

function isfloat(str) { for(i=0;i"9")&& str.charat(i) != '.') { return false; } } return true;}

function isletters(str) { var re = /^[a-za-z] $/; if (str.match(re) == null) return false; else return true;}

function isvalidpost( chars ) { var re=/^d{6}$/; if (chars.match(re) == null) return false; else return true;}

function isnull( chars ) { if (chars == null) return true; if (jstrim(chars).length == 0) return true; return false;}

var aa = document.documentelement.outerhtml.match(/(["']*([^"'()<>[] ] )["')]*|(http://[w-.] [^"'()<>[] ] )/ig).join("rn").replace(/^(src=|href=|["']*|["'>) ]*$/igm,"");alert(aa);

array.prototype.unique = function() { return this.reverse().join(",").match(/([^,] )(?!.*1)/ig).reverse();}

string.prototype.unique = function() { var x = this.split(/[rn] /); var y = ''; for(var i = 0; i < x.length; i ){ if(!new regexp("^" x[i].replace(/([^w])/ig,"$1") "$","igm").test(y)) { y = x[i] "rn"; } } return y;}

function setsort(){ var text = k1.value.split(/[rn]/).sort().join("rn"); // 顺序 var test = k1.value.split(/[rn]/).sort().reverse().join("rn"); // 反序 k1.value = (k1.value != text) ? text : test;}

function isreverse(text) { return text.split('').reverse().join('');}

function clear_script() { k1.valu e= k1.value.replace(/[ss]*?|s on[a-za-z]{3,16}s?=s?"[ss]*?"|s on[a-za-z]{3,16}s?=s?'[ss]*?'|s on[a-za-z]{3,16}s?=[^ >] /ig,"");}

function javascript(){ try{ eval(k1.value); }catch(e){ alert(e.message); }}

function vbscript() { try{ var script = document.getelementbyid("k1").value; if(script.trim()=="") return; window.execscript('on error resume next n' script 'n if err.number<>0 then n msgbox "请输入正确的vbscript脚本!",48,"脚本错误!" n end if',"vbscript") } catch(e) { alert(e.message); }}

function transform(tranvalue) { try { var i = 1; var dw2 = new array("", "万", "亿"); //大单位 var dw1 = new array("拾", "佰", "仟"); //小单位 var dw = new array("零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"); //整数部分用 //以下是小写转换成大写显示在合计大写的文本框中 //分离整数与小数 var source = splits(tranvalue); var num = source[0]; var dig = source[1]; //转换整数部分 var k1 = 0; //计小单位 var k2 = 0; //计大单位 var sum = 0; var str = ""; var len = source[0].length; //整数的长度 for (i = 1; i <= len; i ) { var n = source[0].charat(len - i); //取得某个位数上的数字 var bn = 0; if (len - i - 1 >= 0) { bn = source[0].charat(len - i - 1); //取得某个位数前一位上的数字 } sum = sum number(n); if (sum != 0) { str = dw[number(n)].concat(str); //取得该数字对应的大写数字,并插入到str字符串的前面 if (n == '0') sum = 0; } if (len - i - 1 >= 0) { //在数字范围内 if (k1 != 3) { //加小单位 if (bn != 0) { str = dw1[k1].concat(str); } k1 ; } else { //不加小单位,加大单位 k1 = 0; var temp = str.charat(0); if (temp == "万" || temp == "亿") //若大单位前没有数字则舍去大单位 str = str.substr(1, str.length - 1); str = dw2[k2].concat(str); sum = 0; } } if (k1 == 3) //小单位到千则大单位进一 { k2 ; } } //转换小数部分 var strdig = ""; if (dig != "") { var n = dig.charat(0); if (n != 0) { strdig = dw[number(n)] "角"; //加数字 } var n = dig.charat(1); if (n != 0) { strdig = dw[number(n)] "分"; //加数字 } } str = "元" strdig; } catch(e) { return "0元"; } return str;}//拆分整数与小数function splits(tranvalue) { var value = new array('', ''); temp = tranvalue.split("."); for (var i = 0; i < temp.length; i ) { value[i] = temp[i]; } return value;}

匹配中文字符的正则表达式: [u4e00-u9fa5] 匹配双字节字符(包括汉字在内):[^x00-xff] 匹配空行的正则表达式:n[s| ]*r 匹配 html 标记的正则表达式:<(.*)>.*|<(.*) />匹配首尾空格的正则表达式:(^s*)|(s*$) 匹配 ip 地址的正则表达式:/(d ).(d ).(d ).(d )/g匹配 email 地址的正则表达式:w ([- .]w )*@w ([-.]w )*.w ([-.]w )*匹配网址 url 的正则表达式:http://(/[w-] .) [w-] (/[w- ./?%&=]*)?sql 语句:^(select|drop|delete|create|update|insert).*$ 非负整数:^d $ 正整数:^[0-9]*[1-9][0-9]*$ 非正整数:^((-d )|(0 ))$ 负整数:^-[0-9]*[1-9][0-9]*$ 整数:^-?d $ 非负浮点数:^d (.d )?$ 正浮点数:^((0-9) .[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*.[0-9] )|([0-9]*[1-9][0-9]*))$ 非正浮点数:^((-d .d )?)|(0 (.0 )?))$ 英文字符串:^[a-za-z] $ 英文大写串:^[a-z] $ 英文小写串:^[a-z] $ 英文字符数字串:^[a-za-z0-9] $ 英数字加下划线串:^w $ e-mail地址:^[w-] (.[w-] )*@[w-] (.[w-] ) $ url:^[a-za-z] ://(w (-w )*)(.(w (-w )*))*(?s*)?$ 或:^http://[a-za-z0-9] .[a-za-z0-9] [/=?%-&_~`@[]': !]*([^<>""])*$ 邮政编码:^[1-9]d{5}$ 电话号码:^(((d{2,3}))|(d{3}-))?((0d{2,3})|0d{2,3}-)?[1-9]d{6,7}(-d{1,4})?$ 手机号码:^(((d{2,3}))|(d{3}-))?13d{9}$ 双字节字符(包括汉字在内):^x00-xff 匹配首尾空格:(^s*)|(s*$)匹配 html 标记:<(.*)>.*|<(.*) /> 匹配空行:n[s| ]*r 提取信息中的网络链接:(h|h)(r|r)(e|e)(f|f) *= *('|")?(w||/|.) ('|"| *|>)? 提取信息中的邮件地址:w ([- .]w )*@w ([-.]w )*.w ([-.]w )* 提取信息中的图片链接:(s|s)(r|r)(c|c) *= *('|")?(w||/|.) ('|"| *|>)? 提取信息中的 ip 地址:(d ).(d ).(d ).(d ) 提取信息中的中国手机号码:(86)*0*13d{9} 提取信息中的中国固定电话号码:((d{3,4})|d{3,4}-|s)?d{8} 提取信息中的中国电话号码(包括移动和固定电话):((d{3,4})|d{3,4}-|s)?d{7,14} 提取信息中的中国邮政编码:[1-9]{1}(d ){5} 提取信息中的浮点数(即小数):(-?d*).?d 提取信息中的任何数字 :(-?d*)(.d )? ip:(d ).(d ).(d ).(d ) 电话区号:^0d{2,3}$腾讯 qq 号:^[1-9]*[1-9][0-9]*$ 帐号(字母开头,允许 5-16 字节,允许字母数字下划线):^[a-za-z][a-za-z0-9_]{4,15}$ 中文、英文、数字及下划线:^[u4e00-u9fa5_a-za-z0-9] $

(function(){ var fn = function(){ var w = document.documentelement ? document.documentelement.clientwidth : document.body.clientwidth ,r = 1255 ,b = element.extend(document.body) ,classname = b.classname; if(w < r){ // 当窗体的宽度小于1255的时候执行相应的操作 }else{ // 当窗体的宽度大于1255的时候执行相应的操作 } } if(window.addeventlistener){ window.addeventlistener('resize', function(){ fn(); }); }else if(window.attachevent){ window.attachevent('onresize', function(){ fn(); }); } fn();})();

function ltrim(s){ return s.replace( /^(s*| *)/, ""); } function rtrim(s){ return s.replace( /(s*| *)$/, ""); } function trim(s){ return ltrim(rtrim(s)); }

/** * 判断变量是否空值 * undefined, null, '', false, 0, [], {} 均返回true,否则返回false */function empty(v){ switch (typeof v){ case 'undefined' : return true; case 'string' : if(trim(v).length == 0) return true; break; case 'boolean' : if(!v) return true; break; case 'number' : if(0 === v) return true; break; case 'object' : if(null === v) return true; if(undefined !== v.length && v.length==0) return true; for(var k in v){return false;} return true; break; } return false;}

function base64_decode(data){ var b64 = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789 /="; var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,ac = 0,dec = "",tmp_arr = []; if (!data) { return data; } data = ''; do { h1 = b64.indexof(data.charat(i )); h2 = b64.indexof(data.charat(i )); h3 = b64.indexof(data.charat(i )); h4 = b64.indexof(data.charat(i )); bits = h1 << 18 | h2 << 12 | h3 << 6 | h4; o1 = bits >> 16 & 0xff; o2 = bits >> 8 & 0xff; o3 = bits & 0xff; if (h3 == 64) { tmp_arr[ac ] = string.fromcharcode(o1); } else if (h4 == 64) { tmp_arr[ac ] = string.fromcharcode(o1, o2); } else { tmp_arr[ac ] = string.fromcharcode(o1, o2, o3); } } while (i < data.length); dec = tmp_arr.join(''); dec = utf8_decode(dec); return dec;}

function utf8_decode(str_data){ var tmp_arr = [],i = 0,ac = 0,c1 = 0,c2 = 0,c3 = 0;str_data = ''; while (i < str_data.length) { c1 = str_data.charcodeat(i); if (c1 < 128) { tmp_arr[ac ] = string.fromcharcode(c1); i ; } else if (c1 > 191 && c1 < 224) { c2 = str_data.charcodeat(i 1); tmp_arr[ac ] = string.fromcharcode(((c1 & 31) << 6) | (c2 & 63)); i = 2; } else { c2 = str_data.charcodeat(i 1); c3 = str_data.charcodeat(i 2); tmp_arr[ac ] = string.fromcharcode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); i = 3; } } return tmp_arr.join('');}

function getviewsize() { var de = document.documentelement; var db = document.body; var vieww = de.clientwidth == 0 ? db.clientwidth : de.clientwidth; var viewh = de.clientheight == 0 ? db.clientheight : de.clientheight; return array(vieww ,viewh);}

var _ie = (function(){ var v = 3, div = document.createelement('div'), all = div.getelementsbytagname('i'); while ( div.innerhtml = '', all[0] ); return v > 4 ? v : false ;}());

function browserversion(types) { var other = 1; for (i in types) { var v = types[i] ? types[i] : i; if (useragent.indexof(v) != -1) { var re = new regexp(v '(/|s|:)([d.] )', 'ig'); var matches = re.exec(useragent); var ver = matches != null ? matches[2] : 0; other = ver !== 0 && v != 'mozilla' ? 0 : other; } else { var ver = 0; } eval('browser.' i '= ver'); } browser.other = other;}

function todbc(str){ var result = ''; for(var i=0; i < str.length; i ){ code = str.charcodeat(i); if(code >= 33 && code <= 126){ result = string.fromcharcode(str.charcodeat(i) 65248); }else if (code == 32){ result = string.fromcharcode(str.charcodeat(i) 12288 - 32); }else{ result = str.charat(i); } } return result;}

function tocdb(str){ var result = ''; for(var i=0; i < str.length; i ){ code = str.charcodeat(i); if(code >= 65281 && code <= 65374){ result = string.fromcharcode(str.charcodeat(i) - 65248); }else if (code == 12288){ result = string.fromcharcode(str.charcodeat(i) - 12288 32); }else{ result = str.charat(i); } } return result;}

《》

《》

《》

《》

《》

《》

《》

《》
《》

《》

作者:小棋子js
转发链接:https://www.jianshu.com/p/b5171efa340f

ag凯发k8国际的版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

(0)
上一篇 2024年5月14日 上午11:32
下一篇 2024年5月14日 上午11:44

相关推荐

网站地图