Skip to content

Instantly share code, notes, and snippets.

@amrza
Last active June 22, 2018 20:20
Show Gist options
  • Save amrza/9b5940b102286f9f37160b5e2b7e81a0 to your computer and use it in GitHub Desktop.
Save amrza/9b5940b102286f9f37160b5e2b7e81a0 to your computer and use it in GitHub Desktop.
Convert numbers to FA/EN [alternative]
/**
* Convert English numbers to Persian.
*
* @param {string} value
* @return {string} converted string.
*/
function faNumbers(value) {
if (typeof value === "number") {
var value = value.toString();
}
return value.split('').reduce(function(result, char) {
var charCode = char.charCodeAt(0)
if (charCode >= 48 && charCode <= 57) { // when charachter is 0 to 9
return result + String.fromCharCode(charCode + 1728)
}
return result + char;
}, "");
}
/**
* Convert Persian/Arabic numbers to English.
*
* @param {string} value
* @return {string} converted string.
*/
function enNumbers(value) {
return value.split('').reduce(function(result, char) {
var charCode = char.charCodeAt(0)
if (charCode >= 1776 && charCode <= 1785) { // when charachter is ۰ to ۹ (persian nums)
return result + String.fromCharCode(charCode - 1728)
}
if (charCode >= 1632 && charCode <= 1641) { // when charachter is ٠ to ٩ (arabic nums)
return result + String.fromCharCode(charCode - 1584)
}
return result + char;
}, "");
}
var log = console.log;
log(enNumbers("٠١٢٣٤٥٦٧٨٩")); // arabic
log(enNumbers("۰۱۲۳۴۵۶۷۸۹.")); // persian
log(faNumbers("0123456789"));
log(faNumbers("a123.44.51n"));
log(faNumbers("1397/10/01"));
log(faNumbers("1397-03-25"));
log(faNumbers("600,000,000"));
log(faNumbers(1234567890)); // by int input.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment