漂亮的代码5:数组与字符一样的操作

字符串替换方法
本文介绍了一种使用JavaScript实现的字符串批量替换方法,通过自定义函数tr实现了字符串中指定字符的批量替换,并提供了两种不同的实现方式。一种是利用正则表达式进行全局替换,另一种则是采用split和join方法来实现。

看到这题:


// 依次替换第一个参数中的字符串,用第二个参数。
var str = "TRaduttore"

str.tr( "auioe", "4-103" )  // -> "TR4d-tt0r3"
str.tr( "aeiouR", ["A","E","I","O","U","r"] )  // -> "TrAdUttOrE"

var hi = "Hello Happy CodeWarriors"

hi.tr( ["ello","Happy","Wa","ior"],["ola","Felices","Gue","ero"]) // -> "Hola Felices CodeGuerreros"
hi.tr( ["ll","pp","rr"], "LPR" )  // -> "HeLo HaPy CodeWaRiors"

这是我解决的方案:

String.prototype.tr1 = function(fromList, toList) {
    fromList = fromList || [];
    toList = toList || [];

    var pairs = {};

    var a = Array.isArray(fromList) ? fromList : fromList.split("");
    var b = Array.isArray(toList) ? toList : toList.split("");

    a.forEach((x, i) => pairs[x] = b[i]);

    return a.reduce((acc, cur) => acc.replace(new RegExp(cur, "g"), function(x) {
        return pairs[x] + "" || ""; // 这里如果 toList 中包括 0 的话就不行,所以加上一个空字符转成字符,在这里卡了很久。
    }), this);

}

看别人的解决方案:

String.prototype.tr = function(from, to) {
    for (var s = this, i = 0; i < from.length; i++) {
        s = s.split(from[i]).join(to ? to[i] : '');
    }

    return s;
}

// 我自己改进一下
String.prototype.tr = function(from, to) {
    return (Array.isArray(from) ? from : from.split("")).reduce((acc, cur, i) => acc.split(cur).join(to ? to[i] : ''), this);
}

自己写成了一堆屎,好好学习。

转载于:https://www.cnblogs.com/htoooth/p/5546646.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值