Replacing Letters In A String Using Two Arrays?
Solution 1:
If you're fine with map
:
functionencode (string) {
returnstring.split("").map(function (letter) {
return arr1[arr2.indexOf(letter)];
}).join("");
}
Solution 2:
This should be self explanatory and relatively efficient.
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("");
I'd use a mapping for this kind of thing though.
Solution 3:
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);
Solution 4:
Probably a more straight forward approach is to put the original string into an array first so you can manipulate it more easily character by character:
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";
vardata = 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("");
Working demo: http://jsfiddle.net/jfriend00/fAQTe/
Solution 5:
It depends on your definition of "efficient." With that structure, it's quite hard to be efficient. But something like this is functional and short:
var rex = newRegExp("[" + arr1.join("") + "]", "g");
var result = str.replace(rex, function(letter) {
var index = arr1.indexOf(letter);
return index === -1 ? letter : arr2[index];
});
There, we create a regular expression using a character class to match each of the source characters, then do a replacement operation using a function to look up the replacement (if any) from the arrays.
Now, if you can change the structure, there are better ways, like using a map rather than arr1.indexOf
. E.g.:
varmap = {
"e": "m",
"t": "i",
"a": "e",
// ...
};
Then (this uses ES5's Object.keys
, which can be shimmed if needed):
var rex = newRegExp("[" + Object.keys(map).join("") + "]", "g");
var result = str.replace(rex, function(letter) {
return map[letter] || letter;
});
Post a Comment for "Replacing Letters In A String Using Two Arrays?"