Have to share the JavaScript common method function set (top) _javascript tips

Source: Internet
Author: User
Tags getdate html tags set cookie

This article, the collection of some of the more commonly used JavaScript functions, I hope to learn from the friends of JS help.
1. String length Intercept

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< c15/>} else {break
      ;
    }
  }
  return Strre + "..."
}

2. Replace All

String.prototype.replaceAll = function (S1, S2) {return
  this.replace (new RegExp (S1, "GM"), S2)
}

3. Clear Space

String.prototype.trim = function () {
  var reextraspace =/^\s* (. *?) \s+$/;
  Return This.replace (Reextraspace, "$")
}

4. Clear left space/right space

function LTrim (s) {return s.replace (/^ (\s*| *)/, "");} 
function RTrim (s) {return s.replace (/(\s*| *) $/, "");}

5. Determine whether to start with a string

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, ' < ') . replace (/>/g, ' > ')
}

8. Time Date format conversion

Date.prototype.Format = function (formatstr) {var str = FORMATSTR;
  var Week = [' Day ', ' one ', ' two ', ' three ', ' four ', ' five ', ' six ']; str = str.replace (/yyyy|
  yyyy/, This.getfullyear ()); str = str.replace (/yy| yy/, (this.getyear ()%) > 9?
  (This.getyear ()%). 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 number type

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

10. Set 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 * * * 1000);
  Document.cookie = name + "=" + Escape (value) + ";p ath=/;expires=" + exp.togmtstring () + ";d omain=360doc.com;"
}

11. Get 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 ("Join collection failed, 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, if you want to enable this feature, enter About:config in the Address bar, and then Signed.applets.codebase_principal_support Value is true "
        }
    }
    var prefs = components.classes[' @mozilla. Org/preferences-service;1 '].getservice ( Components.interfaces.nsIPrefBranch);
    Prefs.setcharpref (' browser.startup.homepage ', ' http://w3cboy.com ')
  }

14. Load 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 script Content

function Evalscript (s) {
  if (s.indexof (' <script ') = = 1) return s;
  var p =/<script[^\>]*?> ([^\x00]*?) <\/script>/ig;
  var arr = [];
  while (arr = p.exec (s)) {
    var p1 =/<script[^\>]*?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 =/<script (. *?) > ([^\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.*?>.*?<\/script>/ig, ');
}

17. Dynamically Loading 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. Returns 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 Delete 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 an on method for 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 the entire content of this article, like the collection bar!

Related Article

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.