I have to share the JavaScript common method function set to help you better learn javascript program design. If you are interested, refer to this article and collect some commonly used Javascript Functions, I hope it will help my friends who are learning JS.
1. String Length Truncation
function cutstr(str, len) { var temp, icount = 0, patrn = /[^\x00-\xff]/, strre = ""; 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 } strre += temp } else { break; } } return strre + "..."}
2. replace all
String.prototype.replaceAll = function(s1, s2) { return this.replace(new RegExp(s1, "gm"), s2)}
3. Clear Spaces
String.prototype.trim = function() { var reExtraSpace = /^\s*(.*?)\s+$/; return this.replace(reExtraSpace, "$1")}
4. Clear left or right Spaces
function ltrim(s){ return s.replace( /^(\s*| *)/, ""); } function rtrim(s){ return s.replace( /(\s*| *)$/, ""); }
5. Determine whether a string starts
String.prototype.startWith = function (s) { return this.indexOf(s) == 0}
6. Determine whether to end with a string
String.prototype.endWith = function (s) { var d = this.length - s.length; return (d >= 0 && this.lastIndexOf(s) == d)}
7. Escape html tags
function HtmlEncode(text) { return text.replace(/&/g, '&').replace(/\"/g, '"').replace(//g, '>')}
8. time and date format conversion
Date. prototype. format = function (formatStr) {var str = formatStr; var Week = ['day', 'yi', '2', '3', '4', '5 ', '6']; 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}
9. Determine whether the data type is Numeric
function isDigit(value) { var patrn = /^[0-9]*$/; if (patrn.exec(value) == null || value == "") { return false } else { return true }}
10. Set the cookie value
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;"}
11. Obtain the cookie value
function getCookie(name) { var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)")); if (arr != null) return unescape(arr[2]); return null}
12. Add to favorites
Function AddFavorite (sURL, sTitle) {try {window. external. addFavorite (sURL, sTitle)} catch (e) {try {window. sidebar. addPanel (sTitle, sURL, "")} catch (e) {alert ("failed to add to favorites, please add with Ctrl + D ")}}}
13. Set as Homepage
Function setHomepage () {if (document. all) {document. body. style. behavior = 'url (# default # homepage) '; document. body. setHomePage ('HTTP: // w3cboy.com ')} else if (window. sidebar) {if (window. netscape) {try {netscape. security. privilegeManager. enablePrivilege ("UniversalXPConnect")} catch (e) {alert ("this operation is rejected by the browser. To enable this function, enter about: config in the address bar, then, set the item signed. applets. codebase_principal_support value: true ")} var prefs = Components. classes ['@ mozilla.org/preferences-service%1'%.getservice (Components. interfaces. nsIPrefBranch); prefs. setCharPref ('browser. startup. homepage ', 'HTTP: // w3cboy.com ')}}
14. Load the Style File
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) }}
15. Return the script content
function evalscript(s) { if(s.indexOf('
]*?>([^\x00]*?)<\/script>/ig; var arr = []; while(arr = p.exec(s)) { var p1 = /
]*?src=\"([^\>]*?)\"[^\>]*?(reload=\"1\")?(?:charset=\"([\w\-]+?)\")?><\/script>/i; var arr1 = []; arr1 = p1.exec(arr[0]); if(arr1) { appendscript(arr1[1], '', arr1[2], arr1[3]); } else { p1 = /
([^\x00]+?)<\/script>/i; arr1 = p1.exec(arr[0]); appendscript('', arr1[2], arr1[1].indexOf('reload=') != -1); } } return s;}
16. Clear script content
function stripscript(s) { return s.replace(/
.*?<\/script>/ig, '');}
17. Dynamic Loading of script files
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) {}}
18. Return the Element Object retrieved by ID
function $(id) { return !id ? null : document.getElementById(id);}
19. cross-browser binding events
function addEventSamp(obj,evt,fn){ if(!oTarget){return;} if (obj.addEventListener) { obj.addEventListener(evt, fn, false); }else if(obj.attachEvent){ obj.attachEvent('on'+evt,fn); }else{ oTarget["on" + sEvtType] = fn; } }
20. cross-browser deletion events
function delEvt(obj,evt,fn){ if(!obj){return;} if(obj.addEventListener){ obj.addEventListener(evt,fn,false); }else if(oTarget.attachEvent){ obj.attachEvent("on" + evt,fn); }else{ obj["on" + evt] = fn; }}
21. Add the on Method to the element
Element.prototype.on = Element.prototype.addEventListener; NodeList.prototype.on = function (event, fn) {、 []['forEach'].call(this, function (el) { el.on(event, fn); }); return this;};
The above is all the content of this article. If you like it, add it to favorites!