Arabic to Indic conversion (Latin) sall script digits

by Manuel Souto Pico

HTML

<!DOCTYPE html>
<html lang="ar-EG">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>

<h4>
The two sentences below should be identical in ar-EG:
</h4>

<div>
  Input:
  <div dir="rtl">
مساحة اليابسة ١٣٥ كم² أو كيلومتراً مربعاً.
  <br/>
  احسب المسافة بين النقطتين (س₁, ص₁) و (س₂, ص₂).
  </div>
</div>
    
<div>
  Expected output: 
  <div dir="rtl">
  مساحة اليابسة ١٣٥ كم<sup>٢</sup>
   أو كيلومتراً مربعاً.
  <br/>
  احسب المسافة بين النقطتين (س<sub>١</sub>, ص<sub>١</sub>) و (س<sub>٢</sub>, ص<sub>٢</sub>).
  </div>
</div>
</body>
</html>

JavaScript

const sup_table = { "⁰": "٠", "¹": "١", "²": "٢", "³": "٣", "⁴": "٤", "⁵": "٥", "⁶": "٦", "⁷": "٧", "⁸": "٨", "⁹": "٩" }
const sub_table = { "₀": "٠", "₁": "١", "₂": "٢", "₃": "٣", "₄": "٤", "₅": "٥", "₆": "٦", "₇": "٧", "₈": "٨", "₉": "٩" }

function convertSupArab2indic(inputText) {

		// only for Arabic versions
		if (document.documentElement.lang.split("-")[0] == "ar") {
  		
      // Create a regular expression from the keys of the table
      const regex = new RegExp(Object.keys(sup_table).join('|'), 'g');

      // Replace each match using the table
      return inputText.replace(regex, match => "<sup>" + sup_table[match] + "</sup>");    
    }
}

function convertSubArab2indic(inputText) {

		// only for Arabic versions
		if (document.documentElement.lang.split("-")[0] == "ar") {
  		
      // Create a regular expression from the keys of the table
      const regex = new RegExp(Object.keys(sub_table).join('|'), 'g');

      // Replace each match using the table
      return inputText.replace(regex, match => "<sub>" + sub_table[match] + "</sub>");    
    }
}

// Example usage:
let input = document.body.innerHTML;
input = convertSupArab2indic(input);
document.body.innerHTML = convertSubArab2indic(input);