zoukankan      html  css  js  c++  java
  • javascript 字符串 数字反转 字母大小写互换

    // 符串abcd123ABCD456   怎么转换为 ABCD321abcd654
    // 数字要倒序 小写转大写, 大写转小写
    Array.prototype.reverse = function() {
        var tmp;
        for (var i = 0, j = this.length - 1; i < j; i++, j--) {
            tmp = this[i];
            this[i] = this[j];
            this[j] = tmp;
        }
        return this;
    };
    
    function foo(s) {
        var code, a = [],
            b, last = 0; // 0 1:alpha 2:num
    
        for (var i = 0; i < s.length; i++) {
            code = s.charCodeAt(i);
            if ((97 <= code && code <= 97 + 26 - 1) || (65 <= code && code <= 65 + 26 - 1)) {
                if (last !== 1) {
                    b = [], b.push(code), a.push(b);
                } else {
                    a[a.length - 1].push(code);
                }
                last = 1;
            } else if (48 <= code && code <= 48 + 9) {
                if (last !== 2) {
                    b = [], b.push(code), a.push(b);
                } else {
                    a[a.length - 1].push(code);
                }
                last = 2;
            } else {
                if (last !== 0) {
                    b = [], b.push(code), a.push(b);
                } else {
                    a[a.length - 1].push(code);
                }
                last = 0;
            }
        }
    
        s = a.map(function(a) {
            var c = a[0];
            if (48 <= c && c <= 48 + 9) {
                return a.reverse();
            } else if (97 <= c && c <= 97 + 26 - 1) {
                return a.map(function(c) {
                    return (c &= 0xdf);
                });
            } else if (48 <= c && c <= 48 + 26 - 1) {
                return a.map(function(c) {
                    return (c |= 0x20);
                });
            }
            return a;
        }).map(function(a) {
            return a.map(function(c) {
                return String.fromCharCode(c);
            }).join('');
        }).join('');
        return s;
    }
    
    var s = "abcd123ABCD456";
    console.log(foo(s));
    

      

    > node char.js
    ABCD321abcd654

  • 相关阅读:
    循环神经网络
    相似度计算(余弦距离/欧式距离)
    最常见Linux操作
    注意力机制总结
    随机打乱数组算法、蓄水池算法
    6.1 数据结构---树(遍历)
    Node.js调用C/C++
    linux中nmcli命令详解
    stylus入门使用方法
    webpack CommonsChunkPlugin详细教程
  • 原文地址:https://www.cnblogs.com/mingzhanghui/p/9334905.html
Copyright © 2011-2022 走看看