用两个数组替换字符串中的字母?

时间:2014-01-11 16:39:49

标签: javascript arrays string replace

    var str = "ajdisoiureenvmcnmvm"
    var arr1 = ["e","t","a","i","n","o","h","r","d","q","l","c","u","m","w","f","s","g","y","p","b","v","k","j","x","z"]
    var arr2 = ["m","i","e","n","v","r","d","j","s","o","u","c","b","a","f","g","h","k","l","p","q","t","w","x","z","y"]

更换字符串的最有效方法是什么,如果它包含“m”,则将其替换为“e”,将“i”替换为“t”,依此类推。

6 个答案:

答案 0 :(得分:1)

如果您对map

没问题
function encode (string) {
  return string.split("").map(function (letter) {
    return arr1[arr2.indexOf(letter)];
  }).join("");
}

答案 1 :(得分:0)

这取决于您对“有效”的定义。有了这种结构,就很难有效率。但是像这样的东西是功能和简短:

var rex = new RegExp("[" + arr1.join("") + "]", "g");
var result = str.replace(rex, function(letter) {
    var index = arr1.indexOf(letter);
    return index === -1 ? letter : arr2[index];
});

Live Example | Live Source

在那里,我们使用字符类创建一个正则表达式来匹配每个源字符,然后使用函数执行替换操作以从数组中查找替换(如果有)。

现在,如果你可以改变结构,有更好的方法,比如使用地图而不是arr1.indexOf。 E.g:

var map = {
    "e": "m",
    "t": "i",
    "a": "e",
    // ...
};

然后(这使用ES5的Object.keys,如果需要可以填充):

var rex = new RegExp("[" + Object.keys(map).join("") + "]", "g");
var result = str.replace(rex, function(letter) {
    return map[letter] || letter;
});

答案 2 :(得分:0)

这应该是自我解释的并且相对有效。

str = str.split("")
for(var i = 0; i < str.length; i++) {
    var c = str[i];
    var j = arr1.indexOf(c);
    str[i] = arr2[j];
}
str = str.join("");

我会使用映射来处理这种事情。

答案 3 :(得分:0)

var str = "ajdisoiureenvmcnmvm"
var arr1 = ["e","t","a","i","n","o","h","r","d","q","l","c","u","m","w","f","s","g","y","p","b","v","k","j","x","z"]
var arr2 = ["m","i","e","n","v","r","d","j","s","o","u","c","b","a","f","g","h","k","l","p","q","t","w","x","z","y"]

newStr = str.split("");
for (var i=0, len=newStr.length; i<len; i++)
{
    index = arr2.indexOf(newStr[i]);
    if(index>=0)
        newStr[i] = arr1[index];
}
str = newStr.join("");
console.log(str);

答案 4 :(得分:0)

可能更直接的方法是先将原始字符串放入数组中,这样您就可以更加轻松地逐个操作它:

var arr1 = ["e","t","a","i","n","o","h","r","d","q","l","c","u","m","w","f","s","g","y","p","b","v","k","j","x","z"];
var arr2 = ["m","i","e","n","v","r","d","j","s","o","u","c","b","a","f","g","h","k","l","p","q","t","w","x","z","y"];
var str = "ajdisoiureenvmcnmvm";
var data = str.split(""), index;
for (var i = 0; i < arr2.length; i++) {
    index = str.indexOf(arr2[i]);
    if (index >= 0) {
        data[index] = arr1[i];
    }
}
// build the string back again
str = data.join("");

工作演示:http://jsfiddle.net/jfriend00/fAQTe/

答案 5 :(得分:0)

我知道你没有要求shell脚本的方法,但它会让你觉得在这个特殊请求中tr命令可以轻松完成。

echo "ajdisoiureenvmcnmvm" |tr "etainohrdqlcumwfsgypbvkjxz" "mienvrdjsoucbafghklpqtwxzy"

exsnhrnbjmmvtacvata