Home > Web Front-end > JS Tutorial > 100 Practical JS Custom Functions You Can't Miss_Javascript Skills

100 Practical JS Custom Functions You Can't Miss_Javascript Skills

WBOY
Release: 2016-05-16 16:56:50
Original
1217 people have browsed it

1. Native JavaScript implements string length interception

Copy code The code is as follows:

function cutstr(str, len) {
var temp;
var icount = 0;
var patrn = /[^x00-xff]/;
var 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
                                                           strre = temp
       } else {
                                                                                                                                                🎜> }
}
return strre "..."
}

2. Native JavaScript to obtain the domain name host



Copy Code
The code is as follows:function getHost(url) { var host = "null";
if(typeof url == "undefined" || null == url) {
url = window.location.href;
}
var regex = /^w ://([^/]*).*/;
var match = url.match(regex);
if(typeof match != "undefined" && null != match) {
host = match[1];
}
return host;
}

3. Native JavaScript clear spaces



Copy code
The code is as follows:String.prototype.trim = function() { var reExtraSpace = /^s*(.*?)s $/;
return this.replace(reExtraSpace, "$1")
}

4. Replace all



with native JavaScript .prototype.replaceAll = function(s1, s2) {
return this.replace(new RegExp(s1, "gm"), s2)}5. Native JavaScript escape html tags
Copy code


The code is as follows:


function HtmlEncode(text) {
return text. replace(/&/g, '&').replace(/"/g, '"').replace(//g, '>' )}6. Native JavaScript restores html tags
Copy code


The code is as follows:


function HtmlDecode(text) {
return text.replace(/&/g, '&').replace(/"/g, '"').replace(//g, '>')}7. Native JavaScript time and date format conversion
Copy code


The code is as follows:

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
}

8、原生JavaScript判断是否为数字类型
复制代码 代码如下:

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

9、原生JavaScript设置cookie值
复制代码 代码如下:

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;"
}

10、原生JavaScript获取cookie值
复制代码 代码如下:

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

11、原生JavaScript加入收藏夹
复制代码 代码如下:

function AddFavorite(sURL, sTitle) {
    try {
        window.external.addFavorite(sURL, sTitle)
    } catch(e) {
        try {
            window.sidebar.addPanel(sTitle, sURL, "")
        } catch(e) {
            alert("加入收藏失败,请使用Ctrl D进行添加")
        }
    }
}

12、原生JavaScript设为首页
复制代码 代码如下:

function setHomepage() {
if (document.all) {
document.body.style.behavior = 'url(#default#homepage)';
document.body.setHomePage ('http://www.jq-school.com')
} else if (window.sidebar) {
                                                                                                                                                 .enablePrivilege("UniversalXPConnect")
     } catch(e) {
      alert("This operation is rejected by the browser. If you want to enable this feature, please enter about:config in the address bar, and then sign the item. The value of applets.codebase_principal_support should be true")
                                                                                                                                                                                 codebase
prefs.setCharPref('browser.startup.homepage', 'http://www.jq-school.com')
}
}

13. Native JavaScript determines IE6



Copy code
The code is as follows:var ua = navigator.userAgent.toLowerCase();var isIE6 = ua.indexOf("msie 6") > -1;
if (isIE6) {
try {
document.execCommand("BackgroundImageCache", false, true)
} catch(e) {}
}

14. Native JavaScript loading style file



Copy code
code As follows: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. Native JavaScript returns script content



Copy code
The code is as follows:function evalscript(s) { if(s.indexOf(' var p = /]*?>([^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;
}

16. Native JavaScript Clear script content



Copy code
The code is as follows:function stripscript(s) { return s.replace(/.*?/ig, '');
}

17. Native JavaScript dynamically loads script files



Copy code
The code is as follows:

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. = false;
      scriptNode.onload = function () {
        scriptNode. = true;
        JSLOADED[src] = 1;
      };
      scriptNode.onreadystatechange = function () {
        if((scriptNode.readyState == 'loaded' || scriptNode.readyState == 'complete') && !scriptNode. {
          scriptNode. = true;
          JSLOADED[src] = 1;
        }
      };
    } else if(text){
      scriptNode.text = text;
    }
    document.getElementsByTagName('head')[0].appendChild(scriptNode);
  } catch(e) {}
}


18、原生JavaScript返回按ID检索的元素对象
复制代码 代码如下:

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

19、原生JavaScript返回浏览器版本内容
复制代码 代码如下:

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;
}

20、原生JavaScript元素显示的通用方法
复制代码 代码如下:

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' : '';
  }
}

21、原生JavaScript中有insertBefore方法,可惜却没有insertAfter方法?用如下函数实现
复制代码 代码如下:

function insertAfter(newChild,refChild){
  var parElem=refChild.parentNode;
  if(parElem.lastChild==refChild){
    refChild.appendChild(newChild);
  }else{
    parElem.insertBefore(newChild,refChild.nextSibling);
  }
}

22、原生JavaScript中兼容浏览器绑定元素事件
复制代码 代码如下:

function addEventSamp(obj,evt,fn){
  if (obj.addEventListener) {
    obj.addEventListener(evt, fn, false);
  }else if(obj.attachEvent){
    obj.attachEvent('on' evt,fn);
  }
}

23. The native JavaScript cursor stops behind the text and is called when the text box gets focus. 🎜>
function focusLast(){ var e = event.srcElement; var r =e.createTextRange(); r.moveStart('character',e.value. length); r.collapse(true); r.select();}
24. Native JavaScript checks whether the URL link is valid




Copy code

The code is as follows:

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);
}
}
}

25. Native JavaScript formatting CSS style code




Copy code

The code is as follows:

function formatCss(s){//Formatting code s = s. replace(/s*([{}:;,])s*/g, "$1"); s = s.replace(/;s*;/g, ";"); //Clear consecutive Semicolon 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;
}

26. Native JavaScript compressed CSS style code




Copy code

The code is as follows:

function yasuoCss (s ) {//Compressed code s = s.replace(//*(.|n)*?*//g, ""); //Delete comments s = s.replace(/s* ([{}:;,])s*/g, "$1"); s = s.replace(/,[s.#d]*{/g, "{"); //Fault tolerance processing s = s.replace(/;s*;/g, ";"); //Clear consecutive semicolons s = s.match(/^s*(S (s S )*)s *$/); //Remove the leading and trailing blanks return (s == null) ? "" : s[1];
}

27. Get the current path with native JavaScript




Copy code

The code is as follows:

var currentPageUrl = "";if (typeof this.href = == "undefined") { currentPageUrl = document.location.toString().toLowerCase();}else { currentPageUrl = this.href.toString().toLowerCase(); }
28. Convert native JavaScript IP to integer




Copy code

The code is as follows:

29. Native JavaScript integers are parsed into IP addresses




Copy code

The code is as follows:

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;
}

30. Native JavaScript implements checkbox selection and deselecting all
Copy code The code is as follows:

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;
}
}
}

Note: Mobile Chapter (31~40)
31. Native JavaScript determines whether the device is mobile

Copy code Code As follows:

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 & LT; 600;
var isMobileUserAgent = false;
this._isMobile = isMobileScreenSize && this.isTouchScreen();
return this._isMobile;
}

32. Native JavaScript determines whether mobile device access


Copy code The code is as follows:function isMobileUserAgent(){
return (/iphone |ipod|android.*mobile|windows.*phone|blackberry.*mobile/i.test(window.navigator.userAgent.toLowerCase()));
}

33. Native JavaScript determines whether Apple mobile device access


Copy code The code is as follows:function isAppleMobileDevice(){
return (/iphone|ipod|ipad|Macintosh/i.test(navigator.userAgent.toLowerCase()));
}

34. Native JavaScript determines whether Android mobile device access


Copy code The code is as follows:function isAndroidMobileDevice(){
return (/android/i.test( navigator.userAgent.toLowerCase()));
}

35. Native JavaScript determines whether the screen is touched


Copy code The code is as follows:function isTouchScreen(){
return (('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch);
}

36. Native JavaScript to determine whether Google Chrome on Android is running


Copy the code The code is as follows: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;
}

37. Native JavaScript Determine whether to open the window



Copy the code The code is as follows:

function isViewportOpen() {
return !!document.getElementById('wixMobileViewport');
}

38. Native JavaScript gets the mobile device initialization size
Copy code The code is as follows:

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;
}

39. Native JavaScript to get the maximum size of mobile devices
Copy code The code is as follows:

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 = FixViewPort sExperiment && (FixViewPortsExperiment === "New" || FixViewPortsExperiment === "new");
if(FixViewPortsExperimentRunning){
return screenWidth / window.innerWidth;
}else{
return screenWidth / document .body.offsetWidth;
}
}

40. Native JavaScript to get the mobile device screen width
Copy code The code is as follows:

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;
}

41. Native JavaScript perfectly determines whether Copy the code for the URL
The code is as follows:

function IsURL(strUrl) {
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; Object




Copy code


The code is as follows:

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 ) {
                                                                                                                       }
                                                                                                                                                       🎜>Copy code


The code is as follows:


String.prototype.startWith = function (s) {
return this.indexOf(s) == 0
}

44. Native JavaScript determines whether it ends with a certain string The code is as follows:


String.prototype.endWith = function (s) {
var d = this.length - s.length;
return (d >= 0 && this.lastIndexOf(s ) == d)
}
45. Native JavaScript returns the version number of IE browser Copy code
The code is as follows:


function getIE(){
if (window.ActiveXObject){
var v = navigator.userAgent.match(/MSIE ([^;] )/ )[1];
return parseFloat(v.substring(0, v.indexOf(".")))
}
Copy code


The code is as follows:


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);Copy code


The code is as follows:


function getPageScrollLeft(){
var a = document;
return a.documentElement.scrollLeft || a.body.scrollLeft;
}
48. Native JavaScript to get the visible width of the pageCopy the code
The code is as follows:


function getPageViewWidth(){
var d = document, a = d.compatMode == "BackCompat"
? d.body
: d.documentElement;
return a.clientWidth;Copy the code


The code is as follows:


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);Copy code


The code is as follows:

function getPageScrollTop(){
var a = document;
return a.documentElement.scrollTop || a.body.scrollTop;
}

61. Native JavaScript Solve the offsetX compatibility problem
Copy the code The code is as follows:

// Firefox does not support offsetX /Y
function getOffset(e){
var target = e.target, // Current triggered target object
eventCoord,
pageCoord,
offsetCoord;

// Calculate the distance from the current trigger element to the document
pageCoord = getPageCoord(target);

// Calculate the distance from the cursor to the document
eventCoord = {

// Subtract to obtain the coordinates of the cursor to the first positioned parent element
offsetCoord = {

X : eventCoord.X - pageCoord.X,

Y : eventCoord.Y - pageCoord.Y
};
return offsetCoord;
}

function getPageCoord(element){
var coord = { The sum of offsetLeft or offsetTop values

while (element){

coord.X = element.offsetLeft;
coord.Y = element.offsetTop;
element = element.offsetParent;
}
return coord;
}

62. Regular expressions commonly used in native JavaScript



Copy code
The code is as follows: //positive integer/^[0-9]*[1-9][0-9]*$/;//negative integer
/^-[0-9]*[1-9][0-9]*$/;
//Positive floating point number
/^(([0-9] .[0-9] *[1-9][0-9]*)|([0-9]*[1-9][0-9]*.[0-9] )|([0-9]*[1- 9][0-9]*))$/;
//Negative floating point number
/^(-(([0-9] .[0-9]*[1-9][0- 9]*)|([0-9]*[1-9][0-9]*.[0-9] )|([0-9]*[1-9][0-9]*) ))$/;
//Floating point number
/^(-?d )(.d )?$/;
//email address
/^[w-] (.[w -] )*@[w-] (.[w-] ) $/;
//url address
/^[a-zA-z] ://(w (-w )*)( .(w (-w )*))*(?S*)?$/;
//Year/month/day (year-month-day, year.month.day)
/^(19 |20)dd[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$ /;
//Match Chinese characters
/[u4e00-u9fa5]/;
//Whether the matching account is legal (starting with a letter, 5-10 bytes allowed, alphanumeric underscores allowed)
/ ^[a-zA-Z][a-zA-Z0-9_]{4,9}$/;
//Regular expression matching blank lines
/ns*r/;
/ /Match Chinese postal code
/[1-9]d{5}(?!d)/;
//Match ID card
/d{15}|d{18}/;
//Match domestic phone number
/(d{3}-|d{4}-)?(d{8}|d{7})?/;
//Match IP address
/((2[0-4]d|25[0-5]|[01]?dd?).){3}(2[0-4]d|25[0-5]|[01]? dd?)/;
//Regular expression matching leading and trailing whitespace characters
/^s*|s*$/;
//Regular expression matching HTML tags
< (S *?)[^>]*>.*?|< .*? />;

63. Native JavaScript implements a general method of returning to the top



Copy code
The code is as follows: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');

64. Native JavaScript obtains the GET parameter value in the URL



Copy code
The code is as follows:

// Usage: If the address is test.htm?t1=1&t2=2&t3=3, then you can get: GET["t1"], GET["t2"], GET["t3"]
function get_get(){
querystr = window.location.href.split("?")
if(querystr[1]){
GETs = querystr[1].split("&" )
GET =new Array()
for(i=0;i tmp_arr = GETs[i].split("=")
key=tmp_arr [0]
GET[key] = tmp_arr[1]
}
}
return querystr[1];
}

65. Native JavaScript implements universal selection of all Method
Copy code The code is as follows:

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;
}
}
}

66. Native JavaScript implements a common method to unselect all
Copy code The code is as follows:

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

67. Native JavaScript implements a common method for opening a form
Copy code The code is as follows:

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();
}
}

68. Native JavaScript determines whether it is a client device
Copy code The code is as follows:

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;
}

69. Native JavaScript gets the value of the radio button
Copy Code The code is as follows:

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 ;
}
}

70. Get the value of the checkbox with native JavaScript
Copy the code The code is as follows:

function get_checkbox_value(field){
if(field&&field.length){
for(var i=0;i if(field[i].checked && !field [i].disabled){
            return field[i].value; >(71~80) Verification This article is mainly about 10 commonly used form verification functions, including email, dangerous characters, verification length, verification URL, verification of decimals, integers, floating point numbers and other commonly used verifications. With these Code snippets, normal form validation does not require jquery validation plug-in, I hope it can help everyone. . .
71. Native JavaScript determines whether it is an email address




Copy the code


The code is as follows:
}
}

72. Native JavaScript determines whether there are dangerous characters in the list




Copy code

The code is as follows:
}
}

73. Native JavaScript determines whether the string is greater than the specified length




Copy code

The code is as follows:
74. Native JavaScript determines that the string is case-insensitive for the URL




Copy code

The code is as follows:
function isValidURL( chars ) { 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;
}

75. Native JavaScript Determine whether the string is a decimal




Copy code

The code is as follows:
function isValidDecimal( chars ) { var re=/^d*.?d{1,2}$/; if (chars.match(re) == null) return false; else return true;
}

76. Native JavaScript determines whether a string is an integer




Copy code

The code is as follows :
function isNumber( chars ) { var re=/^d*$/; if (chars.match(re) == null) return false; else return true;
}

77. Native JavaScript determines whether a string is a floating point number




Copy code

The code is as follows:

function isFloat( str ) {
for(i=0;i if ((str.charAt(i)<"0" || str .charAt(i)>"9")&& str.charAt(i) != '.'){
return false;
}
}
return true;
}

78. Native JavaScript determines whether the characters are A-Za-z English letters
Copy code The code is as follows:

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

79. Native JavaScript determines whether a string is a postal code
Copy code The code is as follows:

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

80. Native JavaScript determines whether the character is empty NULL
Copy code The code is as follows:

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

81. Native JavaScript uses regular expressions to extract page code All URLs in
Copy code The code is as follows:

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

82. Native JavaScript uses regular expressions to clear the same array (low efficiency)
Copy code The code is as follows:

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

83. Native JavaScript uses regular expressions to clear the same Array of (high efficiency)
Copy code The code is as follows:

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

84. Native JavaScript uses regular expressions to sort alphabetically and array each line Sort
Copy code The code is as follows:

function SetSort(){
var text= K1.value.split(/[rn]/).sort().join("rn");//Order
var test=K1.value.split(/[rn]/).sort(). reverse().join("rn");//Reverse order
K1.value=K1.value!=text?text:test;
}

85. Reverse native JavaScript string Sequence
Copy code The code is as follows:

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

86. Native JavaScript uses regular expressions to clear scripts in html code
Copy code The code is as follows:

function clear_script(){
K1.value=K1.value.replace(/< script.*?>[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,"");
}

87. Native JavaScript dynamically executes JavaScript scripts
Copy code The code is as follows:

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

88. Native JavaScript dynamically executes VBScript scripts
Copy code The code is as follows:

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 "Please enter the correct VBScript script!",48,"Script error!" n End If',"vbscript")
} catch(e){
alert(e.message);
}
}

89. Native JavaScript implements the amount capitalization conversion function
Copy code The code is as follows:

function transform(tranvalue) {
try {
var i = 1;
var dw2 = new Array("", "10,000", "100 million"); //Large unit
var dw1 = new Array("十", "百", "千"); //Small unit
var dw = new Array("zero", "一", "二", "三" , "四", "五", "鲁", "旒", "八", "九"); //Use
for the integer part //The following is converted from lowercase to uppercase and displayed in the total uppercase text box
//Separate integers and decimals
var source = splits(tranvalue);
var num = source[0];
var dig = source[1];
//Convert the integer part
var k1 = 0; //Small unit
var k2 = 0; //Large unit
var sum = 0;
var str = "";
var len = source [0].length; //The length of the integer
for (i = 1; i <= len; i) {
var n = source[0].charAt(len - i); //Get A number at a certain digit
var bn = 0;
if (len - i - 1 >= 0) {
bn = source[0].charAt(len - i - 1); //Get the number before a certain digit
}
sum = sum Number(n);
if (sum != 0) {
str = dw[Number(n) ].concat(str); //Get the uppercase number corresponding to the number and insert it into the front of the str string
                                                                                                                                                            ]. len - i - 1 >= 0) { //Within the range of numbers
if (k1 != 3) { //Add smaller units
if (bn != 0) {
str = dw1 [k1].concat(str);
}
k1 ;
} else { //Do not add small units, increase units
k1 = 0;
var temp = str.charAt (0); If (TEMP == "Wan" || Temp == "billion") // If there is no number in front of the large unit, go to the large unit
STR = Str.Substr (1, Str. length - 1);
str = dw2[k2].concat(str);
sum = 0;
}
}
if (k1 == 3) //Small unit to One thousand is the next major unit
{
k2 ;
}
}
//Convert the decimal part
var strdig = "";
if (dig != "" ) {
var n = dig.charAt(0);
if (n != 0) {
strdig = dw[Number(n)] "angle"; //Add numbers
}
var n = dig.charAt(1);
if (n != 0) {
strdig = dw[Number(n)] "points"; //Add numbers
}
}
str = "yuan" strdig;
} catch(e) {
return "0 yuan";
}
return str;
}
//Disassemble Split integers and decimals
function splits(tranvalue) {
var value = new Array('', '');
temp = tranvalue.split(".");
for (var i = 0; i < temp.length; i ) {
value[i] = temp[i];
}
return value;
}

90. Native JavaScript Large collection of commonly used regular expressions


Copy code The code is as follows:

Regular expression matching Chinese characters: [u4e00-u9fa5]
Matching double-byte characters (including Chinese characters): [^x00-xff]
Regular expression matching blank lines : [s| ]*r
Regular expression matching HTML tags: <(.*)>.*|<(.*) />
Regular expression matching leading and trailing spaces Expression: (^s*)|(s*$)
Regular expression matching IP address:/(d).(d).(d).(d)/g
Matching Email address Regular expression: w ([- .]w )*@w ([-.]w )*.w ([-.]w )*
Regular expression matching URL: http://(/ [w-] .) [w-] (/[w- ./?%&=]*)?
sql statement: ^(select|drop|delete|create|update|insert).*$
Non-negative integer: ^d $
Positive integer: ^[0-9]*[1-9][0-9]*$
Non-positive integer: ^((-d )|(0 ) )$
Negative integer: ^-[0-9]*[1-9][0-9]*$
Integer: ^-?d $
Non-negative floating point number: ^d (. d )?$
Positive floating point number: ^((0-9) .[0-9]*[1-9][0-9]*)|([0-9]*[1-9] [0-9]*.[0-9] )|([0-9]*[1-9][0-9]*))$
Non-positive floating point number: ^((-d .d )?)|(0 (.0 )?))$
English string: ^[A-Za-z] $
English uppercase string: ^[A-Z] $
English lowercase string: ^ [a-z] $
English character and numeric string: ^[A-Za-z0-9] $
English and numeric string with underline: ^w $
E-mail address: ^[w-] (. [w-] )*@[w-] (.[w-] ) $
URL: ^[a-zA-Z] ://(w (-w )*)(.(w (-w )*))*(?s*)?$ or: ^http://[A-Za-z0-9] .[A-Za-z0-9] [/=?%-&_~`@[] ': !]*([^<>""])*$
Postal code: ^[1-9]d{5}$
Phone number: ^(((d{2,3 }))|(d{3}-))?((0d{2,3})|0d{2,3}-)?[1-9]d{6,7}(-d{1,4 })?$
Mobile phone number: ^(((d{2,3}))|(d{3}-))?13d{9}$
Double-byte characters (including Chinese characters) :^x00-xff
Matches leading and trailing spaces: (^s*)|(s*$)
Matches HTML tags: <(.*)>.*|<(. *) />
matches empty lines: [s| ]*r
Extract network links 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 the picture link in the message: (s|S)(r|R)(c|C) *= *('|")?(w|\|/|.) ('| "| *|>)?
Extract the IP address in the information: (d).(d).(d).(d)
Extract the Chinese mobile phone number in the information: (86)*0* 13d{9}
Extract the Chinese landline phone number in the information: ((d{3,4})|d{3,4}-|s)?d{8}
Extract the Chinese phone number in the information Number (including mobile and landline): ((d{3,4})|d{3,4}-|s)?d{7,14}
Extract the Chinese postal code in the information: [1- 9]{1}(d ){5}
Extract floating point numbers (i.e. decimals) in the information: (-?d*).?d
Extract any number in the information: (-?d*) (.d )?
IP: (d ).(d ).(d ).(d )
Telephone area code: ^0d{2,3}$
Tencent QQ number: ^[1- 9]*[1-9][0-9]*$
Account number (starts with a letter, allows 5-16 bytes, allows alphanumeric underscores): ^[a-zA-Z][a-zA-Z0 -9_]{4,15}$

Chinese, English, numbers and underline: ^[u4e00-u9fa5_a-zA-Z0-9] $
91. Native JavaScript implements form change event resize Operation (compatible with all browsers)
Copy code The code is as follows:

(function() {
var fn = function(){
var w = document.documentElement ? document.documentElement.clientWidth : document.body.clientWidth
, r = 1255
,b = Element.extend(document .body)
,classname = b.className
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template