Skip to content

Instantly share code, notes, and snippets.

@itpcc
Created June 4, 2024 14:10
Show Gist options
  • Save itpcc/b41e37ca4729523422a4b3de9f59ff50 to your computer and use it in GitHub Desktop.
Save itpcc/b41e37ca4729523422a4b3de9f59ff50 to your computer and use it in GitHub Desktop.
JS Thai Number to Arabic Number

How to change Thai number to Arabic (or whatever type) in string

Why?

I've create a Telegram bot to easily fetch law on the land by typing law number or keyword. But, since OCS decide to revamp the site, I've to update the code to catch with new method of display.

Normally, whenever Thai number contains in the text (๐๑๒๓๔๕๖๗๘๙), I'll manually replace one by one like this one shown by Mr.Kobkrit. And then, I've read this StackOverflow answer on how to replace "Arabic" number by manipulating character's Unicode number, like Mr. CLarkson would said, I've a brainwave.

How?

"๐๑๒๓๔๕๖๗๘๙".replace(/[\u0E50-\u0E59]/g, function(v) {
    return String.fromCharCode(v.charCodeAt(0) - 0x0E51 + 49);
});

Here's how it works:

  1. replace(/[\u0E50-\u0E59]/g is to find Thai character represent the number which the code fall within 0x0E50 - 0x0E59 as shown in The Unicode Standard document.
  2. function(v) { is the callback function which will be called when said number is found.
  3. v.charCodeAt(0) - 0x0E51 + 49 is to calculate back the Western Arabic code number which is in range of 49 - 59 by get the character's code number minus by Thai Zero code (0x0E50) and plus Western Arabic Zero (49)
  4. String.fromCharCode is to generate the actual character from calculated code and replace That number one.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment