J'ai une chaîne et je veux remplacer tous les caractères à l'intérieur d'une gamme de caractères avec les caractères correspondants dans un autre tableau, comment ferais-je cela?
Exemple d'entrée / sortie: P>
const from = ["ã ", "Ð", "C", "Î", "Ð", "Ф", "Î", "ã ", "Ð", "ã ", "ã ", "Î", "ã ", "N", "Ω", "Î ", "Q", "ã¹", "Σ", "T", "U", "V", "W", "X", "Y", "Z"]; const to = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
3 Réponses :
const from = ["ã ", "Ð", "C", "Î", "Ð", "Ф", "Î", "ã ", "Ð", "ã ", "ã ", "Î", "ã ", "N", "Ω", "Î ", "Q", "ã¹", "Σ", "T", "U", "V", "W", "X", "Y", "Z"]; const to = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]; const translate = input => [...input].map(char => (index => ~index ? to[index] : char)(from.indexOf(char))).join("")
Pourquoi ne pas prendre un objet pour le remplacement?
La réponse originale a demandé des tableaux, en utilisant un objet serait mieux cependant
Vous pouvez créer un mappage des caractères d'entrée vers des caractères de sortie, puis obtenez la valeur correspondante si le caractère existe dans la mappage sous forme de clé:
p>
const from = ["ã ", "Ð", "C", "Î", "Ð", "Ф", "Î", "ã ", "Ð", "ã ", "ã ", "Î", "ã ", "N", "Ω", "Î ", "Q", "ã¹", "Σ", "T", "U", "V", "W", "X", "Y", "Z"]; const to = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]; const mapping = new Map(from.map((c, i) => [c, to[i]])); function translate(input) { return [...input].map(c => mapping.has(c) ? mapping.get(c) : c).join(''); } console.log(translate("ã ello"));
Vous pouvez utiliser p> mapper code> et
remplacer code>
const from = ["ã
", "Ð", "C", "Î", "Ð", "Ф", "Î", "ã
", "Ð", "ã
", "ã
", "Î", "ã
", "N", "Ω", "Î ", "Q", "ã¹", "Σ", "T", "U", "V", "W", "X", "Y", "Z"];
const to = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
const mapper = new Map(from.map((key, index) => [key, to[index]]));
function translate(string) {
return string.replace(/./gu, (g)=> mapper.get(g) || g)
}
console.log(translate("ã
ello"));
console.log(translate("ã
ellÎ "));
Pouvez-vous s'il vous plaît ajouter un exemple d'entrée et de sortie aussi?