Home>

This article is a common JavaScript function method we collected and sorted out in usual projectsEspecially JavaScript methods are often used,Friends who are interested in javascript function method related knowledge

A function is a block of code wrapped in curly braces,The keyword function was used previously:

function functionname ()
{
Here is the code to execute
}

When the function is called,The code inside the function is executed.

Functions can be called directly when an event occurs (such as when the user clicks a button), and can be called from anywhere by javascript.

Tip:JavaScript is case sensitive.The keyword function must be lowercase,And the function must be called in the same case as the function name.

String length truncation

functiocutstr (strlen {
 vatemp, icoun, patr/[^ \ x- \ xff] /, strr "";
 fo (vastr.lengthi ++ {
 i (icounle {
 temstr.substr (i);
 i (patrn.exec (temp=null {
 icounicoun
 els {
 icounicoun
 }
 strr + temp
 els {
 break;
 }
 }
 returstrr "..."
 }

Replace all

string.prototype.replacealfunction (ss {
 returthis.replace (neregexp (s "gm") s)
 }

Clear space

string.prototype.trifunction ({
 vareextraspac/^ \ s * (. *?) \ s + $/;
 returthis.replace (reextraspace "$")
 }
</pre>
</div>
<p>
Clear left/right spaces
</p>
<div>
<pre>
 functioltrim (s) returs.replace/^ (\ s * | *)/"")}
 functiortrim (s) returs.replace/(\ s * | *) $/"")}
</pre>
</div>
<p>
Determine if it starts with a certain string
</p>
<div>
<pre>
string.prototype.startwitfunctio (s {
 returthis.indexof (s =
 }
</pre>
</div>
<p>
Determine whether to end with a certain string
</p>
<div>
<pre>
string.prototype.endwitfunctio (s {
 vathis.lengts.length;
 retur (>&this.lastindexof (s=d)
 }
</pre>
</div>
<p>
Escape html tags
</p>
<div>
<pre>
functiohtmlencode (text {
 returtext.replace (/&/g "&"). replace (/\ "/g" ""). replace (/<&/g "<"). replace (/>/g ">")
 }
</pre>
</div>
<p>
Time and date format conversion
</p>
<div>
<pre>
date.prototype.formafunction (formatstr {
 vastformatstr;
 vawee ["day" "One" "Two" "Three" "Four" "Five" "Six"];
 ststr.replace (/yyyy|yyyy/this.getfullyear ());
 ststr.replace (/yy | yy/(this.getyear ((this.getyear (). tostring ("(this.getyear ());
 ststr.replace (/mm/(this.getmonth ((this.getmonth (). tostring ("(this.getmonth ());
 ststr.replace (/m/g (this.getmonth ());
 ststr.replace (/w | w/gweek [this.getday ()]);
 ststr.replace (/dd|dd/this.getdate (this.getdate (). tostring ("this.getdate ());
 ststr.replace (/d|d/gthis.getdate ());
 ststr.replace (/hh|hh/this.gethours (this.gethours (). tostring ("this.gethours ());
 ststr.replace (/h|h/gthis.gethours ());
 ststr.replace (/mm/this.getminutes (this.getminutes (). tostring ("this.getminutes ());
 ststr.replace (/m/gthis.getminutes ());
 ststr.replace (/ss|ss/this.getseconds (this.getseconds (). tostring ("this.getseconds ());
 ststr.replace (/s|s/gthis.getseconds ());
 returstr
 }

Determine if it is a numeric type

functioisdigit (value {
 vapatr/^ [-] * $/;
 i (patrn.exec (value=nul | valu="" {
 returfalse
 els {
 returtrue
 }
 }
</pre>
</div>
<p>
Set cookie value
</p>
<div>
<pre>
 functiosetcookie (namevaluehours {
 vanedate ();
 vaoffse;
 vautd.gettime ((d.gettimezoneoffset ();
 vanut (offset);
 vaexnedate (nd);
 exp.settime (exp.gettime (hour);
 document.cookinam "= escape (value";path=/;expires=exp.togmtstring (";domain=doc.com;"
 }
</pre>
</div>
<p>
Get cookie value
</p>
<div>
<pre>
functiogetcookie (name {
 vaardocument.cookie.match (neregexp ("(^) nam"=([^;] *) (;| $) "));
 i (ar! nullreturunescape (arr []);
 returnull
 }

Add to favorites

functioaddfavorite (surlstitle {
 tr {
 window.external.addfavorite (surlstitle)
 catch (e {
 tr {
 window.sidebar.addpanel (stitlesurl "")
 catch (e {
 alert ("Add to collection failed,Please use ctrl + d to add ")
 }
 }
 }
</pre>
</div>
<p>
Setup as front page
</p>
<div>
<pre>
functiosethomepage ({
 i (document.all {
 document.body.style.behavio "url (#default #homepage)";
 document.body.sethomepage ("http://wcboy.com")
 elsi (window.sidebar {
 i (window.netscape {
 tr {
 netscape.security.privilegemanager.enableprivilege ("universalxpconnect")
 catch (e {
 alert ("This operation was rejected by the browser,If i want to enable this feature,Please enter about:config in the address bar, then set the value of signed.applets.codebase_principal_suppor to true ")
 }
 }
 vaprefcomponents.classes ["@ mozilla.org/preferences-service;"].getservice(components.interfaces.nsiprefbranch);
 prefs.setcharpref ("browser.startup.homepage" "http://wcboy.com")
 }
 }

Load style file

functioloadstyle (url {
 tr {
 document.createstylesheet (url)
 catch (e {
 vacsslindocument.createelement ("link");
 csslink.re "stylesheet";
 csslink.typ "text/css";
 csslink.hreurl;
 vaheadocument.getelementsbytagname ("head") [];
 head.appendchild (csslink)
 }
 }

Back to script content

functioevalscript (s {
 if (s.indexof ("<script" =-returs;
 va /<script [^ \>] *?>([^ \ x] *?)<\/script>/ig;
 vaar [];
 while (arp.exec (s) {
 vap/<script [^ \>] *?src=\ "([^ \>] *?) \" [^ \>] *?(reload=\ "\")?(?:charset=\ "([\ w \-] +?) \")?><\/script>/i;
 vaarr [];
 arrp.exec (arr []);
 if (arr {
 appendscript (arr [] "" arr [] arr []);
 els {
 p /<script (. *?)>([^ \ x] +?)<\/script>/i;
 arrp.exec (arr []);
 appendscript ("arr [] arr []. indexof (" reload="!-);
 }
 }
 returs;
 }

Clear script content

functiostripscript (s {
 returs.replace (/<script. *?>. *?<\/script>/ig "");
 }
</pre>
</div>
<p>
Loading script files dynamically
</p>
<div>
<pre>
functioappendscript (srctextreloadcharset {
 vaihash (srtext);
 if (! reloa&in_array (idevalscripts) return;
 if (reloa & $(id) {
 $(id) .parentnode.removechild ($(id));
 }
 evalscripts.push (id);
 vascriptnoddocument.createelement ("script");
 scriptnode.typ "text/javascript";
 scriptnode.iid;
 scriptnode.charsecharsecharse (browser.firefodocument.charactersedocument.charset);
 tr {
 if (src {
 scriptnode.srsrc;
 scriptnode.onloaddonfalse;
 scriptnode.onloafunctio ({
 scriptnode.onloaddontrue;
 jsloaded [src;
 };
 scriptnode.onreadystatechangfunctio ({
 if ((scriptnode.readystat="loaded | scriptnode.readystat =" complete "&! scriptnode.onloaddone {
 scriptnode.onloaddontrue;
 jsloaded [src;
 }
 };
 elsif (text) {
 scriptnode.textext;
 }
 document.getelementsbytagname ("head") []. appendchild (scriptnode);
 catch (e {}
 }

Returns the element object retrieved by id

functio $(id {
 retur! inuldocument.getelementbyid (id);
 }
</pre>
</div>
<p>
Cross browser binding events
</p>
<div>
<pre>
functioaddeventsamp (obj, evt, fn) {
 if (! otarget) {return;}
 i (obj.addeventlistener {
 obj.addeventlistener (evtfnfalse);
 } elsif (obj.attachevent) {
 obj.attachevent ("on" + evt, fn);
 } else {
 otarget ["onsevttypefn;
 }
 }

Cross browser delete event

functiodelevt (obj, evt, fn) {
 if (! obj) {return;}
 if (obj.addeventlistener) {
 obj.addeventlistener (evt, fn, false);
 } elsif (otarget.attachevent) {
 obj.attachevent ("onevt, fn);
 } else {
 obj ["onevtfn;
 }
 }

Add on method to element

element.prototype.oelement.prototype.addeventlistener;
 nodelist.prototype.ofunctio (eventfn {, [] ["foreach"]. call (thisfunctio (el {
 el.on (eventfn);
 });
 returthis;
 };

Add a trigger method to the element

element.prototype.triggefunctio (typedata {
 vaevendocument.createevent ("htmlevents");
 event.initevent (typetruetrue);
 event.datdat | {};
 event.eventnamtype;
 event.targethis;
 this.dispatchevent (event);
 returthis;
 };
 nodelist.prototype.triggefunctio (event {
 [] ["foreach"]. call (thisfunctio (el {
 el ["trigger"] (event);
 });
 returthis;
 };

Check if the URL link is valid

functiogeturlstate (url) {
 vaxmlhttneactivexobject ("microsoft.xmlhttp");
 xmlhttp.open ("get", urlfalse);
 try {
 xmlhttp.send ();
 } catch (e) {
 } finally {
 varesulxmlhttp.responsetext;
 if (result) {
 if (xmlhttp.status ==) {
 return (true);
 } else {
 return (false);
 }
 } else {
 return (false);
 }
 }
 }

Format css style code

.functioformatcss (s) {//formatting code
 s.replace (/\ s * ([\ {\} \:\;\,]) \ s */g "$");
 s.replace (/;\ s *;/g ";") //Remove consecutive semicolons
 s.replace (/\, [\ s \. \ #\ d] * {/g "{");
 s.replace (/([^ \ s]) \ {([^ \ s])/g "${\ n \ t $");
 s.replace (/([^ \ s]) \} ([^ \ n] *)/g "$\ n} \ n $");
 s.replace (/([^ \ s]);([^ \ s \}])/g "$;\ n \ t $");
 returs;
 }

Compressed css style code

functiocompresscs (s {//compress code
 s.replace (/\/\ * (. | \ n) *?\ * \ //g "") //Remove comment
 s.replace (/\ s * ([\ {\} \:\;\,]) \ s */g "$");
 s.replace (/\, [\ s \. \ #\ d] * \ {/g "{") //Fault tolerance
 s.replace (/;\ s *;/g ";") //Remove consecutive semicolons
 s.match (/^ \ s * (\ s + (\ s + \ s +) *) \ s * $/) //Remove leading and trailing spaces
 retur (= null "s [];
 }
</pre>
</div>
<p>
Get the current path
</p>
<div>
<pre>
vacurrentpageur "";
 i (typeothis.hre == "undefined" {
 currentpageurdocument.location.tostring (). tolowercase ();
 } els {
 currentpageurthis.href.tostring (). tolowercase ();
 }

Determine if the device is mobile

functioismobile () {
 i (typeothis._ismobil == "boolean") {
 returthis._ismobile;
 }
 vascreenwidtthis.getscreenwidth ();
 vafixviewportsexperimenrenderermodel.runningexperiments.fixviewpor || renderermodel.runningexperiments.fixviewport;
 vafixviewportsexperimentrunninfixviewportsexperimen&(fixviewportsexperiment.tolowercase (== "new");
 if (! fixviewportsexperiment) {
 if (! this.isapplemobiledevice ()) {
 screenwidtscreenwidth/window.devicepixelratio;
 }
 }
 vaismobilescreensizscreenwidt;
 vaismobileuseragenfalse;
 this._ismobilismobilescreensiz&this.istouchscreen ();
 returthis._ismobile;
 }

Determine if mobile device access

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

Determine if Apple mobile device access

functioisapplemobiledevice () {
 retur (/iphone|ipod|ipad|macintosh/i.test (navigator.useragent.tolowercase ()));
 }
</pre>
</div>
<p>
Determine if Android mobile device access
</p>
<div>
<pre>
 functioisandroidmobiledevice () {
 retur (/android/i.test (navigator.useragent.tolowercase ()));
 }

Determine whether to touch the screen

functioistouchscreen () {
 retur (("ontouchstartiwindow | window.documenttouc&documeninstanceodocumenttouch);
 }

Determine whether to open the window

functioisviewportopen ({
 retur !! document.getelementbyid ("wixmobileviewport");
 }
</pre>
</div>
<p>
Get mobile device initialization size
</p>
<div>
<pre>
functiogetinitzoom () {
 if (! this._initzoom) {
 vascreenwidtmath.min (screen.heightscreen.width);
 if (this.isandroidmobiledevice (&! this.isnewchromeonandroid ()) {
 screenwidtscreenwidth/window.devicepixelratio;
 }
 this._initzooscreenwidt/document.body.offsetwidth;
 }
 returthis._initzoom;
 }

Get mobile device to maximize size

functiogetzoom () {
 vascreenwidt (math.abs (window.orientation == math.max (screen.heightscreen.widthmath.min (screen.heightscreen.width);
 if (this.isandroidmobiledevice (&! this.isnewchromeonandroid ()) {
 screenwidtscreenwidth/window.devicepixelratio;
 }
 vafixviewportsexperimenrenderermodel.runningexperiments.fixviewpor | renderermodel.runningexperiments.fixviewport;
 vafixviewportsexperimentrunninfixviewportsexperimen&(fixviewportsexperimen == "new | fixviewportsexperimen ==" new ");
 if (fixviewportsexperimentrunning) {
 returscreenwidtwindow.innerwidth;
 } else {
 returscreenwidtdocument.body.offsetwidth;
 }
 }

Get mobile device screen width

functiogetscreenwidth () {
 vasmallersidmath.min (screen.widthscreen.height);
 vafixviewportsexperimenrenderermodel.runningexperiments.fixviewpor | renderermodel.runningexperiments.fixviewport;
 vafixviewportsexperimentrunninfixviewportsexperimen&(fixviewportsexperiment.tolowercase (== "new");
 if (fixviewportsexperiment) {
 if (this.isandroidmobiledevice (&! this.isnewchromeonandroid ()) {
 smallersidsmallerside/window.devicepixelratio;
 }
 }
 retursmallerside;
 }

Perfectly determine if it is a URL

functioisurl (strurl {
 varegula/^ \ b (((https?| ftp):\/\ /)?[-az-] + (\. [-az-] +) * \. (? ;:com | edu | gov | int | mil | net | org | biz | info | name | museum | asia | coop | aero | [az] [az] | (([-]) | ([-] \ d) | (\ d \ d) | ([-] \ d) | \ d)) \ b (\/[-az -_:\@&& #63;= + ,.! \/~%\ $] *)?) $/i
 i (regular.test (strurl) {
 returtrue;
 } els {
 returfalse;
 }
 }
getelementsbyclassname
 .functiogetelementsbyclassname (name {
 vatagdocument.getelementsbytagname ("*" | document.all;
 vael [];
 fo (vatags.lengthi ++ {
 i (tags.classname {
 vactags.classname.split (");
 fo (vacs.lengthj ++ {
 i (nam=cs [j] {
 els.push (tags);
 break
 }
 }
 }
 }
 returels
}

Get page height

functiogetpageheight () {
 vadocumentg.bodyg.documentelementg.compatmod="backcompat"
 a
 g.documentelement;
 returmath.max (f.scrollheighta.scrollheightd.clientheight);
 }

Get page scrollleft

functiogetpagescrollleft () {
 vadocument;
 retura.documentelement.scrolllef | a.body.scrollleft;
 }
</pre>
</div>
<p>
Get page visible width
</p>
<div>
<pre>
functiogetpageviewwidth () {
 vadocumentd.compatmod="backcompat"
 d.body
 d.documentelement;
 retura.clientwidth;
 }

Get page width

functiogetpagewidth () {
 vadocumentg.bodyg.documentelementg.compatmod="backcompat"
 a
 g.documentelement;
 returmath.max (f.scrollwidtha.scrollwidthd.clientwidth);
 }

Get page scrolltop

functiogetpagescrolltop () {
 vadocument;
 retura.documentelement.scrollto | a.body.scrolltop;
 }

Get page view height

functiogetpageviewheight ({
 vadocumentd.compatmod="backcompat"
 d.body
 d.documentelement;
 retura.clientheight;
 }

Remove url prefix

functioremoveurlprefix (a) {
 a=a.replace (/:/g, ":"). replace (/./g, "."). replace (///g, "/");
 while (trim (a) .tolowercase (). indexof ("http://") ==) {
 a=trim (a.replace (/http:\/\ //i, ""));
 }
 retura;
 }

Random number timestamp

functiouniqueid () {
 vaa=math.random, b=parseint;
 returnumber (nedate ()). tostring () + b (* a ()) + b (* a ()) + b (* a ());
 }
</pre>
</div>
<p>
Full-width half-angle conversion
</p>
<div>
<pre>
//icase full to half, half to full, others do not convert
 functiochgcase (sstr, icase) {
 if (typeosst! "string | sstr.lengt<|! (icas == | icas =)) {
 retursstr;
 }
 vai, ors=[], icode;
 if (icase) {/* half->full * /
 for (i=i<sstr.length;i + =) {
 icodsstr.charcodeat (i);
 if (icod =) {
 icod;
 } elsif (icod) {
 icod +;
 }
 ors.push (string.fromcharcode (icode));
 }
 } else {/* full->half * /
 for (i=i<sstr.length;i + =) {
 icodsstr.charcodeat (i);
 if (icod =) {
 icod;
 } elsif (icod&icod) {
 icod-;
 }
 ors.push (string.fromcharcode (icode));
 }
 }
 returors.join ("");
 }

Check if the keyboard is valid

functiocheckkey (ikey) {
 if (ike=| ike =) {returtrue;}/* spaces and exceptions * /
 if (ikey>&ike) {returtrue;}/* number * /
 if (ikey>&ike) {returtrue;}/* letter * /
 if (ikey>&ike) {returtrue;}/* numerical keyboard * /
 if (ikey>&ike) {returtrue;}/* numerical keyboard * /
 if (ikey>&ike) {returtrue;}/* symbol * /
 if (ikey>&ike) {returtrue;}/* symbol * /
 returfalse;
 }
</pre>
</div>
<p>
Get where the webpage was rolled
</p>
<div>
<pre>
 functiogetscrollxy ({
 returdocument.body.scrollto {
 xdocument.body.scrollleft, ydocument.body.scrolltop
 } {
 xdocument.documentelement.scrollleft, ydocument.documentelement.scrolltop
 }
 }
</pre>
</div>
<p>
Date formatting function + calling method
</p>
<div>
<pre>
date.prototype.formafunction (format) {
 va {
 "m + this.getmonth () + //month
 "d + this.getdate () //day
 "h + this.gethours () //hour
 "m + this.getminutes () //minute
 "s + this.getseconds () //second
 "q + math.floor ((this.getmonth () +) /) //quarter
 "sthis.getmilliseconds (//millisecond
 };
 if (/(y +) /. test (format) format=format.replace (regexp. $, (this.getfullyear () + ""). substr (regexp. $. length));
 for (vaio) {
 if (neregexp ("(" + ")"). test (format))
 formaformat.replace (regexp. $, regexp. $. length == o [k :( "" o [k]). substr (("" o [k]). length));
 }
 returformat;
 }
 alert (nedate (). format ("yyyy-mm-dhh:mm:ss"));

Time personalized output function

./*
 ., S is displayed as "just now"
 .>mi&min shows the difference from the current time "xx minutes ago"
 .>mi&day shows the current time difference "today xx:xx"
 .,>da&year display the date "xx month xxxx:xx"
 .>year shows the specific date "xxxxyearxxmonthxxxx:xx"
 . * /
 .functiotimeformat (time) {
 vadatnedate (time), curdatnedate (), yeadate.getfullyear (), montdate.getmonth (, dadate.getdate (), houdate.gethours (), minutdate.getminutes (), curyeacurdate.getfullyear (), curhoucurdate.gethours (), timestr;
 if (yeacuryear) {
 timestyea + "year" mont + "month" da + "" hou + ":" minute;
 } else {
 vapasttimcurdatdate, pastpasttime /;
 if (pastcurhour) {
 timestmont + "month" da + "" hou + ":" minute;
 } elsif (past>) {
 timest "this hou +":"minut +"Minute ";
 } else {
 vapastcurdate.getminutes (minute;
 if (past) {
 timestpast + "minutes ago";
 } else {
 timest "just";
 }
 }
 }
 returtimestr;
 }

Solving offsetx compatibility issues

./does not support offsetx/y for Firefox
 .functiogetoffset (e) {
 vatargee.target/the target object currently triggered
 eventcoord, pagecoord, offsetcoord;
 /Calculate the distance from the current trigger element to the document
 pagecoorgetpagecoord (target);
 /Calculate the distance from the cursor to the document
 eventcoor {
 window.pagexoffsee.clientx, window.pageyoffsee.clienty
 };
 /Subtract to get the coordinates of the cursor to the first positioned parent
 offsetcoor {
 eventcoord.pagecoord.x, eventcoord.pagecoord.y
 };
 returoffsetcoord;
 .}
 .functiogetpagecoord (element) {
 vacoor};
 /Calculate from the current trigger element to the root node, /The sum of offsetlefoffsetto value of each offsetparen element
 whil (element) {
 coord. + element.offsetleft;
 coord. + element.offsettop;
 elemenelement.offsetparent;
 }
 returcoord;
 .}
Common regular expressions
 .//Positive integer
 ./^[-]*[-][-]*$/;
 .//Negative integer
 ./^-[-]*[-][-]*$/;
 .//Positive Float
 ./^(([-]+\.[-]*[-][-]*) | ([-] * [-] [-] * \. [-] +) | ([-] * [ -] [-] *)) $/;
 .//Negative floating point
 ./^(-(([-]+\.[-]*[-][-]*)|([-]*[-][-]*\.[-]+)|(- * [-] [-] *))) $/;
 .//Float
 ./^(-?\d+)(\.\d+)?$/;
 .//email address
 ./^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;
 .//url address
 ./^[a-za-z]+://(\w+(-\w+)*)(\.(\w+(-\w+)*))*(\?\s*)?$/;
 .Or:^ http:\/\/[a-za-z-] + \. [A-za-z-] + [\/= \?%\-&_ ~ `@ [\] \ ":+!] * ([^<>\" \ "]) *
.//Year/month/day (year-month-day, year.month.day)
 ./^(|)\d\d[/.]([-]|[])[/.]([-]|[][-]|[])$/;
 .//Match Chinese characters
 ./[\ue-\ufa]/;
 .//Match account is legal (beginning with a letter,Allow-byte, allow alphanumeric underscores)
 ./^[a-za-z][a-za-z-_]{,}$/;
 .//Regular expression matching blank lines
 ./\n\s*\r/;
 .//Match China Postcode
 ./[-]\d{}(?!\d)/;
 .//Match ID
 ./\d{}|\d{}/;
 .//Match domestic phone number
 ./(\d{}-|\d{}-)?(\d{}|\d{})?/;
 .//Match ip address
 ./(([-]\d|[-]|[]?\d\d?)\.){}([-]\d|[-]|[]?\ d \ d?) /;
 .//Regular expression that matches leading and trailing whitespace characters
 ./^\s*|\s*$/;
 .//Regular expression matching html tags
 . (\ s *?) [^>] *>. *?|. * /> ;;
 .//sq statement
 . ^ (select | drop | delete | create | update | insert). * $
 .//Extract the network link in the information
 . (h | h) (r | r) (e | e) (f | f ** ("|")?(\ w | \\ | \/| \.) + ("|" * |>)?
 .//Extract the email address in the message
 . \ w + ([-+.] \ w +) *@\ w + ([-.] \ w +) * \. \ w + ([-.] \ w +) *
 .//Extract image links in information
 . (s | s) (r | r) (c | c ** ("|")?(\ w | \\ | \/| \.) + ("|" * |>)?
 .//Extract information from i address
 . (\ d +) \. (\ d +) \. (\ d +) \. (\ d +)
 .//Get the Chinese mobile number in the information
 . () ** \ d {}
 .//Extract Chinese postal code from information
 . [-] {} (\ d +) {}
 .//Floating point numbers (ie decimals) in the extracted information
 . (-?\ d *) \.?\ d +
 .//Extract any number in the information
 . (-?\ d *) (\. \ D +)?
 .//Phone area code
 . ^ \ d {,} $
 .//Teng q
 . ^ [-] * [-] [-] *
.//Account (beginning with a letter,Allow-byte, allow alphanumeric underscores)
 . ^ [a-za-z] [a-za-z -_] {,}
.//Chinese, English, numbers and underscores
 . ^ [\ ue- \ ufa_a-za-z-] + $
Back to top generic methods
 .functiobacktop (btnid {
 vabtdocument.getelementbyid (btnid);
 vadocument.documentelement;
 vadocument.body;
 window.onscrolset;
 btn.style.displa "none";
 btn.onclicfunction ({
 btn.style.displa "none";
 window.onscrolnull;
 this.timesetinterval (function ({
 d.scrollto-math.ceil ((d.scrolltob.scrolltop.);
 b.scrollto-math.ceil ((d.scrolltob.scrolltop.);
 i ((d.scrolltob.scrolltop=clearinterval (btn.timerwindow.onscrolset);
 });
 };
 functioset ({
 btn.style.displa (d.scrolltob.scrollto "block" "none"
 }
 .};
 .backtop ("gotop");
Get the value of the get parameter in the url
 ./Usage:If the address test.htm?t =&t =&t=then can get:get ["t"] get ["t"] get ["t"]
 .functioget_get () {
 querystwindow.location.href.split ("?")
 if (querystr []) {
 getquerystr []. split ("&");
 ge [];
 for (i =;i<gets.length;i ++) {
 tmp_argets.split ("=")
 key=tmp_arr []
 get [keytmp_arr []
 }
 }
 returquerystr [];
 .}
Open a form general method
 .functioopenwindow (url, windowname, width, height) {
 vaparseint (screen.widt. (widt.);
 vaparseint (screen.heigh. (heigh.);
 vaismsie (navigator.appnam="microsofinterneexplorer");
 i (ismsie {
 va "resizable =, location=no, scrollbars=no, width =";
 p + width;
 p + ", height =";
 p + height;
 p + ", left =";
 p + x;
 p + ", top =";
 p + y;
 retvawindow.open (urlwindownamep);
 els {
 vawiwindow.open (url "zyiispopup" "top =", left=", scrollbars=scrollbar", dialog=yes, modal=yes, width=widt ", height=heigh", resizable=no);
 eval ("trwin.resizeto (widthheight) catch (e)");
 win.focus ();
 }
 .}
Extract all URLs in the page code
 vaadocument.documentelement.outerhtml.match (/(url \ (| src=| href =) [\ "\"] * ([^ \ "\" \ (\) \<\>\ [\] +) [\ "\" \)] * | (http:\/\/[\ w \-\.] + [^ \ "\" \ (\) \<\>\ [\] +)/ig ) .join ("\ r \ n"). replace (/^ (src=| href=| url \ () [\ "\"] * | [\ "\" \>\] * $/igm, "");
 alert (aa);
Clear the same array
 string.prototype.unique=function () {
 vax=this.split (/[\ r \ n] + /);
 vay="";
 for (vai =;i<x.length;i ++) {
 if (! neregexp ("^" + x.replace (/([^ \ w])/ig, "\\ $") + "$", "igm"). test (y)) {
 y +=x + "\ r \ n"
 }
 }
 retury
 };
Alphabetically,Sort array by row
 functiosetsort () {
 vatext=k.value.split (/[\ r \ n] /). sort (). join ("\ r \ n");//order
 vatest=k.value.split (/[\ r \ n] /). sort (). reverse (). join ("\ r \ n");//Reverse order
 k.value=k.value!=text?text:test;
 }
String reverse order
 functioisreverse (text) {
 returtext.split (""). reverse (). join ("");
 }
Clear script from html code
 functioclear_script () {
 k.value=k.value.replace (/<script. *?>[\ s \ s] *?<\/script>| \ s + on [a-za-z ] {,} \ s?= \ s?"[\ s \ s] *?" | \ s + on [a-za-z] {,} \ s?= \ s?"[\ s \ s] *?" | \ s + on [a-za-z] {,} \ s?= [>] +/ig, "");
 }
 Dynamically execute javascript script
 functiojavascript () {
 try {
 eval (k.value);
 } catch (e) {
 alert (e.message);
 }
 }
Dynamically execute vbscript script
 functiovbscript () {
 try {
 vascript=document.getelementbyid ("k"). value;
 if (script.trim () == "") return;
 window.execscript ("oerroresumnex \ n" + script + "\ ierr.number<>the \ msgbo" Please enter the correct vbscript script! ",," Script error! \ enif "," vbscript ")
 } catch (e) {
 alert (e.message);
 }
 }
Amount capitalization conversion function
 functiotransform (tranvalue {
 tr {
 va;
 vadnearray ("" "" "" "Billion") //large unit
 vadnearray ("Pick up" "Bai" "thousand") //Small unit
 vadnearray ("zero" "one" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" //)
 //The following is a text box converted from lowercase to uppercase and displayed in total uppercase
//Separate integers from decimals
 vasourcsplits (tranvalue);
 vanusource [];
 vadisource [];
 //Convert the integer part
 va //small unit
 va //large unit
 vasu;
 vast "";
 valesource []. length //integer length
 fo (<leni ++ {
 vasource []. charat (lei) //Get number in a certain digit
 vab;
 i (l>{
 bsource []. charat (le) //Get the number before the certain digit
 }
 susunumber (n);
 i (su! {
 stdw [number (n)]. concat (str) //Get the uppercase number corresponding to the number,And insert it in front of the str string
 i (= "" su;
 }
 i (l>//in the range of numbers
 i (! //plus small units
 i (b! {
 stdw [k] .concat (str);
 }
 k ++;
 els //without small units,Increase unit
 ;
 vatemstr.charat ();
 i (tem="Ten thousand | tem =" billion "//If there is no number in front of the large unit, the large unit is discarded
 ststr.substr (str.lengt);
 stdw [k] .concat (str);
 su;
 }
 }
 i (=) //small units to thousands of large units
 k ++;
 }
 }
 //Convert the decimal part
 vastrdi "";
 i (di! "" {
 vadig.charat ();
 i (! {
 strdi + dw [number (n) "Angle" //plus number
 }
 vadig.charat ();
 i (! {
 strdi + dw [number (n) "points" //plus numbers
 }
 }
 st + "yuan strdig;
 catch (e {
 retur "yuan";
 }
 returstr;
}
//Split integers and decimals
functiosplits (tranvalue {
 vavalunearray ("" "");
 temtranvalue.split (".");
 fo (vatemp.lengthi ++ {
 valutemp;
 }
 returvalue;
}
resize operation
 (function () {
 vaffunction () {
 vadocument.documentelemendocument.documentelement.clientwidtdocument.body.clientwidth
 , , element.extend (document.body)
 , classnamb.classname;
 if (r) {
 //Perform the corresponding operation when the width of the form is less than
 } else {
 //Perform the corresponding operation when the width of the form is greater than
 }
 }
 if (window.addeventlistener) {
 window.addeventlistener ("resize" function () fn ()});
 } elsif (window.attachevent) {
 window.attachevent ("onresize" function () fn ()});
 }
 fn ();
 }) ();
Implement base64 decoding
 functiobase_decode (data) {
 vab "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz +/=";
 vaooohhhhbits, a, de "", tmp_ar [];
 i (! datareturdata)
 dat + "";
 d {
 hb.indexof (data.charat (i ++));
 hb.indexof (data.charat (i ++));
 hb.indexof (data.charat (i ++));
 hb.indexof (data.charat (i ++));
 bith<h<h<h;
 obit>xff;
 obit>xff;
 obitxff;
 i (h={
 tmp_arr [ac++ string.fromcharcode (o);
 elsi (h={
 tmp_arr [ac++ string.fromcharcode (oo);
 els {
 tmp_arr [ac++ string.fromcharcode (ooo);
 }
 whil (data.length);
 detmp_arr.join ("");
 deutf_decode (dec);
 returdec;
 }
Implement UTF8 decoding
 .functioutf_decode (str_data) {
 vatmp_ar [] ,, a ,,,;str_dat + "";
 whil (str_data.length {
 str_data.charcodeat (i);
 i ({
 tmp_arr [ac++ string.fromcharcode (c);
 i ++;
 elsi&{
 str_data.charcodeat ();
 tmp_arr [ac++ string.fromcharcode (((<< ());
 +;
 els {
 str_data.charcodeat ();
 str_data.charcodeat ();
 tmp_arr [ac++ string.fromcharcode (((<< ((<< ());
 +;
 }
 }
 returtmp_arr.join ("");
 }
Get the width and height of the visible range of the form
 .functiogetviewsize () {
 vade=document.documentelement;
 vadb=document.body;
 vavieww=de.clientwidth == db.clientwidtde.clientwidth;
 vaviewh=de.clientheight == db.clientheighde.clientheight;
 returarray (view, viewh);
 }
Whether the mouse is moved out of the event
 functioismouseout (ehandler {
 i (e.typ!="mouseout" {
 returfalse;
 }
 varelte.relatedtargee.relatedtargee.typ == "mouseoute.toelemene.fromelement;
 whil (relt&relt!=handler {
 reltreltg.parentnode;
 }
 retur (relt!=handler);
 }
Half-angle conversion to full-angle function
 .functiotodbc (str) {
 varesul "";
 for (vai=str.lengthi ++) {
 codstr.charcodeat (i);
 if (cod>&cod<) {
 resul + string.fromcharcode (str.charcodeat (i);
 } elsi (cod =) {
 resul + string.fromcharcode (str.charcodeat (i);
 } else {
 resul + str.charat (i);
 }
 }
 returresult;
 }
Full-Angle to Half-Angle Function
 .functiotocdb (str) {
 varesul "";
 for (vai=str.lengthi ++) {
 codstr.charcodeat (i);
 if (cod&cod&);{
 resul + string.fromcharcode (str.charcodeat (i);
 } elsi (cod =) {
 resul + string.fromcharcode (str.charcodeat ();
 } else {
 resul + str.charat (i);
 }
 }
 returresult;
 }
  • Previous JavaScript image preloading complete example
  • Next C # method for creating database and importing SQL script