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

來源:互聯網
上載者:User

網路上類似的代碼一般都是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;     }

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.