Skip to content

Instantly share code, notes, and snippets.

@amirasaran
Created September 27, 2016 06:23
Show Gist options
  • Save amirasaran/05f97748cd1d268dc3f6c85bdacb197b to your computer and use it in GitHub Desktop.
Save amirasaran/05f97748cd1d268dc3f6c85bdacb197b to your computer and use it in GitHub Desktop.
JavaScript Arabic character to Persian (تبدیل حروف عربی به فارسی)
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.replace(new RegExp(search, 'g'), replacement);
};
String.prototype.toPersianCharacter = function () {
var string = this;
var obj = {
'ك' :'ک',
'دِ': 'د',
'بِ': 'ب',
'زِ': 'ز',
'ذِ': 'ذ',
'شِ': 'ش',
'سِ': 'س',
'ى' :'ی',
'ي' :'ی',
'١' :'۱',
'٢' :'۲',
'٣' :'۳',
'٤' :'۴',
'٥' :'۵',
'٦' :'۶',
'٧' :'۷',
'٨' :'۸',
'٩' :'۹',
'٠' :'۰',
};
Object.keys(obj).forEach(function(key) {
string = string.replaceAll(key, obj[key]);
});
return string
};
/**
* Example
*/
var string = 'ك ٤ ٦٦';
string = string.toPersianCharacter();
console.log(string); //out put "ک ۴ ۶۶"
@majid-rafei
Copy link

Thanks

@parsagholipour
Copy link

parsagholipour commented Sep 19, 2024

const arabicToPersian = str => {
  if (!str) return str;

  const diff = {
    'ك': 'ک',
    'دِ': 'د',
    'بِ': 'ب',
    'زِ': 'ز',
    'ذِ': 'ذ',
    'شِ': 'ش',
    'سِ': 'س',
    'ى': 'ی',
    'ي': 'ی',
    'ئ': 'ی',
    '١': '۱',
    '٢': '۲',
    '٣': '۳',
    '٤': '۴',
    '٥': '۵',
    '٦': '۶',
    '٧': '۷',
    '٨': '۸',
    '٩': '۹',
    '٠': '۰',
  };

  for (const [key, value] of Object.entries(diff)) {
    str = str.replaceAll(key, value);
  }

  return str;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment