[JS]用JavaScript檢查輸入文字是否有日文

同事在問,如何去檢查輸入的內容是否有日文這裡做了一個範例提供參考

緣起

同事在問,如何去檢查輸入的內容是否有日文這裡做了一個範例提供參考

 

UTF-8語言範圍

首先,要知道各國語言在UTF-8的範圍

參考:http://blog.csdn.net/a9529lty/article/details/2680007

/u4e00-/u9fa5 (中文)
/x3130-/x318F (韓文)
/xAC00-/xD7A3 (韓文)
/u0800-/u4e00 (日文)

ps.韓文大於/u9fa5

 

範例

直接看範例如下:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    
</head>
<body>

    <input type="text" id="txt1" />
    <input type="button" id="btn1" value="檢查日文" />


    <script src="../Scripts/jquery-1.10.2.min.js"></script>
    <script>
        function haveChinese(s) {
            return s.search(RegExp("[一-" + String.fromCharCode(40869) + "]")) > -1;
        }

        function chkJPN(s) {
            var re1 = new RegExp("^[\u0800-\\u4e00]*$");     //日文的範圍
            //var s = s.replace(/(^\s*)|(\s*$)/g, '');
            if (s == '') { return false; }
            //console.log(s.substr(0, 1));
            var testChar = '';
            //console.log(s.length);
            var rc;
            for (var i = 0; i < s.length;i++){
                testChar = s.substr(i, 1);
                //console.log(testChar);
                if (!(re1.test(testChar))) {
                    rc = false;
                }
                else
                    return true;
            }
            if (rc == false) {
                return false;
            }
            else
                return true;
        }

        $(document).ready(function () {
            $('#btn1').click(function () {
                var t1 = $('#txt1').val();
                console.log(chkJPN(t1));
            });
        });
    </script>
</body>
</html>

 

 


以下是簽名:


Microsoft MVP
Visual Studio and Development Technologies
(2005~2019/6) 
topcat
Blog:http://www.dotblogs.com.tw/topcat