ArticleZip > How To Convert Persian And Arabic Digits Of A String To English Using Javascript

How To Convert Persian And Arabic Digits Of A String To English Using Javascript

Converting Persian and Arabic digits to English in a string might sound challenging, but with JavaScript, it's actually quite straightforward. This article will guide you through how to achieve this conversion, allowing you to work with different numeral systems in your JavaScript code effortlessly.

To begin, let's first understand the difference between Persian and Arabic digits. Persian digits are commonly used in the Persian language and are different from Arabic numerals. Arabic digits are the numerals we commonly use in English, ranging from 0 to 9.

In JavaScript, you can convert Persian and Arabic digits to English using a simple function. Here's a step-by-step guide to accomplish this task:

Step 1: Define a function that will handle the conversion. You can name it something intuitive like `convertDigitsToEnglish`.

Step 2: Inside the function, create a map that corresponds each Persian and Arabic digit to its English equivalent. You can create an object where keys are the Persian or Arabic digits and values are their English counterparts.

Step 3: Iterate through the input string and replace each Persian or Arabic digit with its English equivalent using the map you created in Step 2.

Step 4: Return the modified string with all digits converted to English.

Below is a sample JavaScript function that demonstrates how to convert Persian and Arabic digits to English in a string:

Javascript

function convertDigitsToEnglish(inputStr) {
    const digitMap = {
        '۰': '0',
        '۱': '1',
        '۲': '2',
        '۳': '3',
        '۴': '4',
        '۵': '5',
        '۶': '6',
        '۷': '7',
        '۸': '8',
        '۹': '9'
    };

    let englishStr = inputStr;

    for (let key in digitMap) {
        const regex = new RegExp(key, 'g');
        englishStr = englishStr.replace(regex, digitMap[key]);
    }

    return englishStr;
}

// Test the function
const originalStr = 'سلام۱۲۳';
const englishStr = convertDigitsToEnglish(originalStr);
console.log(englishStr); // Output: سلام123

You can now use the `convertDigitsToEnglish` function in your JavaScript code to effortlessly convert Persian and Arabic digits to English in any given string. This functionality can be especially useful when working with multilingual data or user inputs.

By following these simple steps and utilizing the provided function, you can easily handle the conversion of numerals in different scripts within your JavaScript projects. Whether you're building a language learning app or working with international data, this technique will streamline your development process and enhance the user experience.

×