JavaScript common method function set (top) _ javascript skills that have to be shared

Source: Internet
Author: User
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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.