inputArray = ["z","d"]; inputArray = ["د","ذ"]; function trans(stri){ inputArray.forEach((value, i) => { var next = i + 1; a1 = inputArray[i]; a2 = outputArray[i]; regex = new XRegExp(a1, "g"); stri = XRegExp.replace(stri, regex, a2, ["all"]) return stri; }); } console.log(trans("dzzd"))
Quiero traducir de caracteres latinos a caracteres árabes, ¿cómo usar {{árabe}}?, y soy muy nuevo en RegExp o incluso en XRegExp. Entonces, ¿cómo lo hago básicamente? También lo siento mucho si soy la falta de experiencia ..
Salida esperada = "دذذد"
Puede hacer todos los reemplazos en una sola pasada, haciendo una alternancia de inputArray
y usando una función de reemplazo para devolver el carácter apropiado de outputArray
en una coincidencia:
function trans(str, from, to) { return str.replace(new RegExp(`${from.join('|')}`, 'g'), function(m) { return to[from.indexOf(m)]; }); } inputArray = ["z", "d"]; outputArray = ["ذ", "د"]; console.log(trans('dzzd', inputArray, outputArray))
Tenga en cuenta que si from
puede contener valores superpuestos (por ejemplo, ab
y a
), debe ordenar from
y to
por la longitud de las cadenas en forma descendente antes from
usarlos. Puedes hacerlo con este código:
// create an array of indexes ids = Array.from({length : from.length}, (_, i) => i) // sort the indexes by the length of the corresponding string in `from` ids.sort((a, b) => from[b].length - from[a].length) // now map from and to to the new order from = from.map((_, i) => from[ids[i]]) to = to.map((_, i) => to[ids[i]])
Esto asegura que la expresión regular siempre coincida con la secuencia más larga por preferencia (ya que aparecerá primero en la alternancia).
Puede insertar en la función trans
, por ejemplo:
function trans(str, from, to) { ids = Array.from({ length: from.length }, (_, i) => i) ids.sort((a, b) => from[b].length - from[a].length) from = from.map((_, i) => from[ids[i]]) to = to.map((_, i) => to[ids[i]]) return str.replace(new RegExp(`${from.join('|')}`, 'g'), function(m) { return to[from.indexOf(m)]; }); } inputArray = ["zz", "d"]; outputArray = ["ذ", "د"]; console.log(trans('dzzd', inputArray, outputArray))
o utilícelo en inputArray
y outputArray
antes de llamar a trans
:
function trans(str, from, to) { return str.replace(new RegExp(`${from.join('|')}`, 'g'), function(m) { return to[from.indexOf(m)]; }); } inputArray = ["zz", "d"]; outputArray = ["ذ", "د"]; ids = Array.from({ length: inputArray.length }, (_, i) => i) ids.sort((a, b) => inputArray[b].length - inputArray[a].length) inputArray = inputArray.map((_, i) => inputArray[ids[i]]) outputArray = outputArray.map((_, i) => outputArray[ids[i]]) console.log(trans('dzzd', inputArray, outputArray))