JavasSript 技巧(3)

1 篇文章 / 0 new
author
JavasSript 技巧(3)
71、原生JavaScript判斷是否為郵箱

    function isEmail(str){
        var re=/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
            if (re.test(str) != true) {
                    return false;
            }else{
                    return true;
            }       
    }

72、原生JavaScript判斷是否有列表中的危險字符

    function isValidReg(chars){
            var re=/<|>|\[|\]|\{|\}|『|』|※|○|●|◎|§|△|▲|☆|★|◇|◆|□|▼|㊣|﹋|⊕|⊙|〒|ㄅ|ㄆ|ㄇ|ㄈ|ㄉ|ㄊ|ㄋ|ㄌ|ㄍ|ㄎ|ㄏ|ㄐ|ㄑ|ㄒ|ㄓ|ㄔ|ㄕ|ㄖ|ㄗ|ㄘ|ㄙ|ㄚ|ㄛ|ㄜ|ㄝ|ㄞ|ㄟ|ㄢ|ㄣ|ㄤ|ㄥ|ㄦ|ㄧ|ㄨ|ㄩ|■|▄|▆|\*|@|#|\^|\\/;
            if (re.test( chars) == true) {
                    return false;
            }else{
                    return true;
            }       
    }

73、原生JavaScript判斷字符串是否大於規定的長度

    function isValidLength(chars, len) {
            if (chars.length < len) {
                    return false;
            }
            return true;
    }

74、原生JavaScript判斷字符串是為網址不區分大小寫

    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、原生JavaScript判斷字符串是否為小數

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

76、原生JavaScript判斷字符串是否為整數

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

77、原生JavaScript判斷字符串是否為浮點數

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

78、原生JavaScript判斷字符是否為A-Za-z英文字母

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

79、原生JavaScript判斷字符串是否郵政編碼

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

80、原生JavaScript判斷字符是否空NULL

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

81、原生JavaScript用正則表達式提取頁面代碼中所有網址

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

82、原生JavaScript用正則表達式清除相同的數組(低效率)

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

83、原生JavaScript用正則表達式清除相同的數組(高效率)

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

84、原生JavaScript用正則表達式按字母排序,對每行進行數組排序

    function SetSort(){
            var text=K1.value.split(/[\r\n]/).sort().join("\r\n");//順序
            var test=K1.value.split(/[\r\n]/).sort().reverse().join("\r\n");//反序
            K1.value=K1.value!=text?text:test;
    }

85、原生JavaScript字符串反序

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

86、原生JavaScript用正則表達式清除html代碼中的腳本

    function clear_script(){
      K1.value=K1.value.replace(/<script.*?>[\s\S]*?<\/script>|\s+on[a-zA-Z]{3,16}\s?=\s?"[\s\S]*?"|\s+on[a-zA-Z]{3,16}\s?=\s?'[\s\S]*?'|\s+on[a-zA-Z]{3,16}\s?=[^ >]+/ig,"");
    }

87、原生JavaScript動態執行JavaScript腳本

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

88、原生JavaScript動態執行VBScript腳本

    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 "請輸入正確的VBScript腳本!",48,"腳本錯誤!" \n End If',"vbscript")
            }catch(e){
                    alert(e.message);
            }
    }

89、原生JavaScript實現金額大寫轉換函數

    function transform(tranvalue) {
      try {
        var i = 1;
        var dw2 = new Array("", "萬", "億"); //大單位
        var dw1 = new Array("拾", "佰", "仟"); //小單位
        var dw = new Array("零", "壹", "貳", "三", "肆", "伍", "陸", "柒", "捌", "玖"); //整數部分用
        //以下是小寫轉換成大寫顯示在合計大寫的文本框中    
        //分離整數與小數
        var source = splits(tranvalue);
        var num = source[0];
        var dig = source[1];
        //轉換整數部分
        var k1 = 0; //計小單位
        var k2 = 0; //計大單位
        var sum = 0;
        var str = "";
        var len = source[0].length; //整數的長度
        for (i = 1; i <= len; i++) {
          var n = source[0].charAt(len - i); //取得某個位數上的數字
          var bn = 0;
          if (len - i - 1 >= 0) {
            bn = source[0].charAt(len - i - 1); //取得某個位數前一位上的數字
          }
          sum = sum + Number(n);
          if (sum != 0) {
            str = dw[Number(n)].concat(str); //取得該數字對應的大寫數字,並插入到str字符串的前面
            if (n == '0') sum = 0;
          }
          if (len - i - 1 >= 0) { //在數字範圍內
            if (k1 != 3) { //加小單位
              if (bn != 0) {
                str = dw1[k1].concat(str);
              }
              k1++;
            } else { //不加小單位,加大單位
              k1 = 0;
              var temp = str.charAt(0);
              if (temp == "萬" || temp == "億") //若大單位前沒有數字則捨去大單位
              str = str.substr(1, str.length - 1);
              str = dw2[k2].concat(str);
              sum = 0;
            }
          }
          if (k1 == 3) //小單位到千則大單位進一
          {
            k2++;
          }
        }
        //轉換小數部分
        var strdig = "";
        if (dig != "") {
          var n = dig.charAt(0);
          if (n != 0) {
            strdig += dw[Number(n)] + "角"; //加數字
          }
          var n = dig.charAt(1);
          if (n != 0) {
            strdig += dw[Number(n)] + "分"; //加數字
          }
        }
        str += "元" + strdig;
      } catch(e) {
        return "0元";
      }
      return str;
    }
    //拆分整數與小數
    function splits(tranvalue) {
      var value = new Array('', '');
      temp = tranvalue.split(".");
      for (var i = 0; i < temp.length; i++) {
        value = temp;
      }
      return value;
    }

90、原生JavaScript常用的正則表達式大收集

    匹配中文字符的正則表達式: [\u4e00-\u9fa5]
    匹配雙字節字符(包括漢字在內):[^\x00-\xff]
    匹配空行的正則表達式:\n[\s| ]*\r
    匹配 HTML 標記的正則表達式:<(.*)>.*<\/\1>|<(.*) \/>
    匹配首尾空格的正則表達式:(^\s*)|(\s*$)
    匹配 IP 地址的正則表達式:/(\d+)\.(\d+)\.(\d+)\.(\d+)/g
    匹配 Email 地址的正則表達式:\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
    匹配網址 URL 的正則表達式:http://(/[\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?
    sql 語句:^(select|drop|delete|create|update|insert).*[        DISCUZ_CODE_39        ]nbsp;
    非負整數:^\d+[        DISCUZ_CODE_39        ]nbsp;
    正整數:^[0-9]*[1-9][0-9]*[        DISCUZ_CODE_39        ]nbsp;
    非正整數:^((-\d+)|(0+))[        DISCUZ_CODE_39        ]nbsp;
    負整數:^-[0-9]*[1-9][0-9]*[        DISCUZ_CODE_39        ]nbsp;
    整數:^-?\d+[        DISCUZ_CODE_39        ]nbsp;
    非負浮點數:^\d+(\.\d+)?[        DISCUZ_CODE_39        ]nbsp;
    正浮點數:^((0-9)+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))[        DISCUZ_CODE_39        ]nbsp;
    非正浮點數:^((-\d+\.\d+)?)|(0+(\.0+)?))[        DISCUZ_CODE_39        ]nbsp;
    英文字符串:^[A-Za-z]+[        DISCUZ_CODE_39        ]nbsp;
    英文大寫串:^[A-Z]+[        DISCUZ_CODE_39        ]nbsp;
    英文小寫串:^[a-z]+[        DISCUZ_CODE_39        ]nbsp;
    英文字符數字串:^[A-Za-z0-9]+[        DISCUZ_CODE_39        ]nbsp;
    英數字加下劃線串:^\w+[        DISCUZ_CODE_39        ]nbsp;
    E-mail地址:^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+[        DISCUZ_CODE_39        ]nbsp;
    URL:^[a-zA-Z]+://(\w+(-\w+)*)(\.(\w+(-\w+)*))*(\?\s*)?$ 或:^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*[        DISCUZ_CODE_39        ]nbsp;
    郵政編碼:^[1-9]\d{5}[        DISCUZ_CODE_39        ]nbsp;
    電話號碼:^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?[        DISCUZ_CODE_39        ]nbsp;
    手機號碼:^((\(\d{2,3}\))|(\d{3}\-))?13\d{9}[        DISCUZ_CODE_39        ]nbsp;
    雙字節字符(包括漢字在內):^\x00-\xff
    匹配首尾空格:(^\s*)|(\s*$)
    匹配 HTML 標記:<(.*)>.*<\/\1>|<(.*) \/>
    匹配空行:\n[\s| ]*\r
    提取信息中的網絡鏈接:(h|H)(r|R)(e|E)(f|F) *= *('|")?(\w|\\|\/|\.)+('|"| *|>)?
    提取信息中的郵件地址:\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
    提取信息中的圖片鏈接:(s|S)(r|R)(c|C) *= *('|")?(\w|\\|\/|\.)+('|"| *|>)?
    提取信息中的 IP 地址:(\d+)\.(\d+)\.(\d+)\.(\d+)
    提取信息中的中國手機號碼:(86)*0*13\d{9}
    提取信息中的中國固定電話號碼:(\(\d{3,4}\)|\d{3,4}-|\s)?\d{8}
    提取信息中的中國電話號碼(包括移動和固定電話):(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}
    提取信息中的中國郵政編碼:[1-9]{1}(\d+){5}
    提取信息中的浮點數(即小數):(-?\d*)\.?\d+
    提取信息中的任何數字 :(-?\d*)(\.\d+)?
    IP:(\d+)\.(\d+)\.(\d+)\.(\d+)
    電話區號:^0\d{2,3}$
    騰訊 QQ 號:^[1-9]*[1-9][0-9]*[        DISCUZ_CODE_39        ]nbsp;
    帳號(字母開頭,允許 5-16 字節,允許字母數字下劃線):^[a-zA-Z][a-zA-Z0-9_]{4,15}[        DISCUZ_CODE_39        ]nbsp;
    中文、英文、數字及下劃線:^[\u4e00-\u9fa5_a-zA-Z0-9]+$

91、原生JavaScript實現窗體改變事件resize的操作(兼容所以的瀏覽器)

    (function(){
            var fn = function(){
                    var w = document.documentElement ? document.documentElement.clientWidth : document.body.clientWidth
                            ,r = 1255
                            ,b = Element.extend(document.body)
                            ,classname = b.className;
                    if(w < r){
                            //當窗體的寬度小於1255的時候執行相應的操作
                    }else{
                            //當窗體的寬度大於1255的時候執行相應的操作
                    }
            }
            if(window.addEventListener){
                    window.addEventListener('resize', function(){ fn(); });
            }else if(window.attachEvent){
                    window.attachEvent('onresize', function(){ fn(); });
            }
            fn();
    })();

92、原生JavaScript用正則清除空格分左右

    function ltrim(s){ return s.replace( /^(\s*| *)/, ""); }
    function rtrim(s){ return s.replace( /(\s*| *)$/, ""); }
    function trim(s){ return ltrim(rtrim(s));}

93、原生JavaScript判斷變量是否空值

    /**
    * 判斷變量是否空值
    * undefined, null, '', false, 0, [], {} 均返回true,否則返回false
    */
    function empty(v){
        switch (typeof v){
            case 'undefined' : return true;
            case 'string'    : if(trim(v).length == 0) return true; break;
            case 'boolean'   : if(!v) return true; break;
            case 'number'    : if(0 === v) return true; break;
            case 'object'    :
                if(null === v) return true;
                if(undefined !== v.length && v.length==0) return true;
                for(var k in v){return false;} return true;
                break;
        }
        return false;
    }

94、原生JavaScript實現base64解碼

    function base64_decode(data){
            var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
            var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,ac = 0,dec = "",tmp_arr = [];
            if (!data) { return data; }
            data += '';
            do {
                    h1 = b64.indexOf(data.charAt(i++));
                    h2 = b64.indexOf(data.charAt(i++));
                    h3 = b64.indexOf(data.charAt(i++));
                    h4 = b64.indexOf(data.charAt(i++));
                    bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
                    o1 = bits >> 16 & 0xff;
                    o2 = bits >> 8 & 0xff;
                    o3 = bits & 0xff;
                    if (h3 == 64) {
                            tmp_arr[ac++] = String.fromCharCode(o1);
                    } else if (h4 == 64) {
                            tmp_arr[ac++] = String.fromCharCode(o1, o2);
                    } else {
                            tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
                    }
            } while (i < data.length);
            dec = tmp_arr.join('');
            dec = utf8_decode(dec);
            return dec;
    }

95、原生JavaScript實現utf8解碼

    function utf8_decode(str_data){
            var tmp_arr = [],i = 0,ac = 0,c1 = 0,c2 = 0,c3 = 0;str_data += '';
            while (i < str_data.length) {
                    c1 = str_data.charCodeAt(i);
                    if (c1 < 128) {
                            tmp_arr[ac++] = String.fromCharCode(c1);
                            i++;
                    } else if (c1 > 191 && c1 < 224) {      
                            c2 = str_data.charCodeAt(i + 1);
                            tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
                            i += 2;
                    } else {
                            c2 = str_data.charCodeAt(i + 1);
                            c3 = str_data.charCodeAt(i + 2);
                            tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                            i += 3;
                    }
            }
            return tmp_arr.join('');
    }

96、原生JavaScript獲取窗體可見範圍的寬與高

    function getViewSize(){
            var de=document.documentElement;
            var db=document.body;
            var viewW=de.clientWidth==0 ?  db.clientWidth : de.clientWidth;
            var viewH=de.clientHeight==0 ?  db.clientHeight : de.clientHeight;
            return Array(viewW ,viewH);
    }

96、原生JavaScript判斷IE版本號(既簡潔、又向後兼容!)

    var _IE = (function(){
        var v = 3, div = document.createElement('div'), all = div.getElementsByTagName('i');
        while (
            div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
            all[0]
        );
        return v > 4 ? v : false ;
    }());

97、原生JavaScript獲取瀏覽器版本號

    function browserVersion(types) {
        var other = 1;
        for (i in types) {
            var v = types ? types : 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;
    }

98、原生JavaScript判斷鼠標是否移出事件

    function isMouseOut(e, handler) {
            if (e.type !== 'mouseout') {
                    return false;
            }
            var reltg = e.relatedTarget ? e.relatedTarget : e.type === 'mouseout' ? e.toElement : e.fromElement;
            while (reltg && reltg !== handler) {
                    reltg = reltg.parentNode;
            }
            return (reltg !== handler);
    }

99、原生JavaScript半角轉換為全角函數

    function ToDBC(str){
      var result = '';
      for(var i=0; i < str.length; i++){
        code = str.charCodeAt(i);
        if(code >= 33 && code <= 126){
          result += String.fromCharCode(str.charCodeAt(i) + 65248);
        }else if (code == 32){
          result += String.fromCharCode(str.charCodeAt(i) + 12288 - 32);
        }else{
          result += str.charAt(i);
        }
      }
    return result;
    }

100、原生JavaScript全角轉換為半角函數

    function ToCDB(str){
      var result = '';
      for(var i=0; i < str.length; i++){
        code = str.charCodeAt(i);
        if(code >= 65281 && code <= 65374){
          result += String.fromCharCode(str.charCodeAt(i) - 65248);
        }else if (code == 12288){
          result += String.fromCharCode(str.charCodeAt(i) - 12288 + 32);
        }else{
          result += str.charAt(i);
        }
      }
    return result;
    }

from http://developer.51cto.com/art/201312/425414.htm
Free Web Hosting