-1
votes

Comment remplacer les caractères dans une chaîne avec d'autres caractères dans une chaîne en utilisant deux tableaux d'entrée

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"];


1 commentaires

Pouvez-vous s'il vous plaît ajouter un exemple d'entrée et de sortie aussi?


3 Réponses :


0
votes
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("")

2 commentaires

Pourquoi ne pas prendre un objet pour le remplacement?


La réponse originale a demandé des tableaux, en utilisant un objet serait mieux cependant



0
votes

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"));


0 commentaires

0
votes

Vous pouvez utiliser mapper code> et remplacer code>

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 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Π"));


0 commentaires