javascriptarraysreplacexregexp

xRegExp Replace expression


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

I wanna translate from latin characters to arabic characters, how to use {{Arabic}}?, and I Very new to RegExp or even XRegExp, So how basically i do it? Also I'm very very sorry if im Lack of Experience..

Expected Output = "دذذد"


Solution

  • You can do all the replacements in one pass, making an alternation out of inputArray and using a replacement function to return the appropriate character from outputArray on a match:

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

    Note that if from might contain overlapping values (for example ab and a) you need to sort from and to by the length of the strings in from descending before using them. You can do that with this code:

    // 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]])
    

    This ensures that the regex always matches the longest sequence by preference (since it will come first in the alternation).

    You could either insert into the trans function, for example:

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

    or use it on inputArray and outputArray before you call 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))