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

 

posted @ 2018-07-19 11:40  zhanghui_ming  阅读(1677)  评论(0编辑  收藏  举报