0

I'm trying to replace multi characters from array globally with regular expresion, but it just replace the first character for me:

var ARABIC_PUNC_AND_REPLACEMENTS = [
    [
      ',', // Comma
      ';', // Semicolon
    ],
    [
      '،', // Comma
      '؛', // Semicolon
    ]
  ];

var string = ',,, ;;;';

for (var i = 0; i < ARABIC_PUNC_AND_REPLACEMENTS[0].length; i++) {
   string = string.replace(ARABIC_PUNC_AND_REPLACEMENTS[0][i], ARABIC_PUNC_AND_REPLACEMENTS[1][i]);
}

console.log(string); // "،,, ؛;;"
// I want this to be returnd: "،،، ؛؛؛"
elkebirmed
  • 2,247
  • 6
  • 24
  • 35

1 Answers1

1

You need to construct a RegExp and pass global flag like this:

for (var i = 0; i < ARABIC_PUNC_AND_REPLACEMENTS[0].length; i++) {
   string = string.replace(new RegExp(ARABIC_PUNC_AND_REPLACEMENTS[0][i], 'g'),
     ARABIC_PUNC_AND_REPLACEMENTS[1][i]);
}

console.log(string);
//=> "،،، ؛؛؛"
anubhava
  • 761,203
  • 64
  • 569
  • 643