MahaPrachar
MahaPrachar

Reputation: 39

Convert Hindu–Arabic numerals to English numbers

Inside array there is non english number as string I want convert to english and put it into logic, and perform template string operation forEach div.

Here is sample of my code

const bigdata = [{img:'http://anything/com/123.png',title:'डेंजर ऑफर', inv:'१७५०'}] //Here १७५० = 1750 NOTE: I have multiple objects like this in my code

let template='';
bigdata.forEach(offers => {
function offer_tag(){
    if((HERE I WANT CONVERTED NUMBER)<15000){
       return `<span class="badge badge-warning">नवीन</span>`
    }
}

//This offer tag will be used in template string

I have got a conversion code from jQuery but I am very confused how can I use this code to convert string number to English number and use inside if statement. Here is jQuery code: (I copied from JavaScript - replace to English number)

    var numbers = {
      '०': 0,
      '१': 1,
      '२': 2,
      '३': 3,
      '४': 4,
      '५': 5,
      '६': 6,
      '७': 7,
      '८': 8,
      '९': 9
    };

    function replaceNumbers(input) {
      var output = [];
      for (var i = 0; i < input.length; ++i) {
        if (numbers.hasOwnProperty(input[i])) {
          output.push(numbers[input[i]]);
        } else {
          output.push(input[i]);
        }
      }
      return output.join('');
    }

    document.getElementById('r').textContent = replaceNumbers('१७५०');

Upvotes: 1

Views: 325

Answers (2)

JonSG
JonSG

Reputation: 13087

The code you have is very close already. Try:

function parseIntHindi(text, radix){
  var numbers = { '०': 0, '१': 1, '२': 2, '३': 3, '४': 4, '५': 5, '६': 6, '७': 7, '८': 8, '९': 9 };

  function replaceNumbers(input) {
    var output = [];
    for (var i = 0; i < input.length; ++i) {
      if (numbers.hasOwnProperty(input[i])) {
        output.push(numbers[input[i]]);
      } else {
        output.push(input[i]);
      }
    }
    return output.join('');
  }

  return parseInt(replaceNumbers(text), radix)
}

console.log(parseIntHindi("१७५०"));
console.log(parseIntHindi("१७५०") +1);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386570

You could generate new objects with converted properties, if possible.

function replaceNumbers(input) {
    var numbers = { '०': '0', '१': '1', '२': '2', '३': '3', '४': '4', '५': '5', '६': '6', '७': '7', '८': '8', '९': '9' };
    return Array.from(input, c => numbers[c] || c).join('');
}

const
    bigdata = [{img:'http://anything/com/123.png',title:'डेंजर ऑफर', inv:'१७५०'}],
    converted = bigdata.map(o => Object.assign(...Object.entries(o).map(([k, v]) => ({ [k]: replaceNumbers(v) }))))

console.log(converted);

Upvotes: 1

Related Questions