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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fareast_mzh

打赏个金币

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值