JS/Java中,判斷字符串是否包含中文


網絡上類似的代碼一般都是JS判斷字符串是否全為中文,但判斷是否包含中文的代碼很少,這里提供三種方法:

 

<script language="javascript">  
function funcChina(){ 
var obj = document.form1.txtName.value; 
if(/.*[\u4e00-\u9fa5]+.*$/.test(obj)) 
{ 
alert("不能含有漢字!"); 
return false; 
} 
return true; 
} 
</script> 
<form name="form1">
<input type="text" name="txtName"><input type="button" name="butTxt" value="判斷是否是漢字" onclick="funcChina()">
</form>

 

 

<script language="javascript"> 
function isChina(s){ 
var patrn=/[\u4E00-\u9FA5]|[\uFE30-\uFFA0]/gi; 
if(!patrn.exec(s)){ 
return false; 
}
else{ 
return true; 
} 
}
alert(isChina("中國站長天空www.zzsky.cn"));
</script>

 

 

<script language="javascript">
var str='中國站長天空www.zzsky.cn';
if(escape(str).indexOf("%u")<0){ 
alert("沒有包含中文");
}
else{
alert("包含中文");
}
</script>

Java中:

    /**
     * 判斷str是否為中文字符.
     * 
     * @param str
     * @return
     */
    private static boolean chineseEncode(String str){
        
        char[] chars=str.toCharArray(); 
        boolean isGB2312=false; 
        for(int i=0;i<chars.length;i++){
                    byte[] bytes=(""+chars[i]).getBytes(); 
                    if(bytes.length==2){ 
                                int[] ints=new int[2]; 
                                ints[0]=bytes[0]& 0xff; 
                                ints[1]=bytes[1]& 0xff; 
                                if(ints[0]>=0x81 && ints[0]<=0xFE && ints[1]>=0x40 && ints[1]<=0xFE){ 
                                            isGB2312=true; 
                                            break; 
                                } 
                    } 
        } 
        return isGB2312; 
    }

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM