Fork me on GitHub

字符串string

1、字符串获取类、封装检测数字的方法

    var str = '前端开发';
    //alert(str.length);
    //alert(str.charAt());     //没有参数  取得索引是0     结果是:前
    //alert(str.charCodeAt());    //获取到该索引下内容的unicode   结果是:21069
    alert(str.charCodeAt(1));   //结果是:31417
    alert(String.fromCharCode(21069,31471));   //通过unicode得到汉字

 

用unicode检测数字

<input type="text"><input type="button" value="检测">

  

    //检测是否有数字
    var aInp = document.getElementsByTagName('input');
    
    aInp[1].onclick = function(){
        var val = aInp[0].value;
        if(checkNum(val)){
            alert('恭喜,'+val+'全是数字');
        }else{
            alert('输入有误');
        }
    }
    
    function checkNum(str){
        for(var i=0;i<str.length;i++){
            code = str.charCodeAt(i)
            if( code<48 || code>57  ){
                return false;
            }
        }
        return true;
    }

 

3、fromCharCode返回字符串、字符串加密

    <input type="text"><input type="button" value="加密">
    <div id="div1"></div>
    
    var oDiv = document.getElementById('div1');
    var aInp = document.getElementsByTagName('input');
    aInp[1].onclick = function(){
        var str = aInp[0].value;
        var str1 = '';
        for(var i=0;i<str.length;i++){
            str1 += String.fromCharCode(str.charCodeAt(i)-1000);
        }
        oDiv.innerHTML  = str1;
    }

 

posted on 2015-11-15 17:17  雨为我停  阅读(202)  评论(0编辑  收藏  举报