美文网首页javascript
js统计字符串中各种字符出现的情况

js统计字符串中各种字符出现的情况

作者: 3seconds | 来源:发表于2018-03-28 23:37 被阅读109次
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
    </head>
    <body>
        <input type="text" placeholder="请输入字符" id="input1">
        <button id="button1">统计</button>
        <div id="box1"></div>
    
        <script type="text/javascript">
        var btn = document.getElementById('button1'),
            box = document.getElementById('box1');
        btn.onclick = function() {
            var str = document.getElementById('input1').value,
                countChinese = 0,
                countUpper = 0,
                countLower = 0,
                countNumber = 0,
                countOther = 0;
    
            /* 遍历字符串中的每个字符 */
            for (var i = 0, len = str.length; i < len; i++) {
                var char = str.charAt(i);
                if (/[\u4e00-\u9fa5]/.test(char)) {
                    countChinese++;
                } else if (/[A-Z]/.test(char)) {
                    countUpper++;
                } else if (/[a-z]/.test(char)) {
                    countLower++;
                } else if (/[0-9]/.test(char)) {
                    countNumber++;
                } else {
                    countOther++;
                }
            }
            box.innerHTML = '字符串: <b>' + str + '</b> 中含有: <br />汉字个数: ' + countChinese + '<br />大写字母个数: ' + countUpper + '<br />小写字母个数: ' + countLower + '<br />数字: ' + countNumber + '<br />其他字符: ' + countOther
        }
        </script>
    </body>
    </html>
    

    结果如下图:


    image.png

    相关文章

      网友评论

        本文标题:js统计字符串中各种字符出现的情况

        本文链接:https://www.haomeiwen.com/subject/vbjpcftx.html