JavaScript - 替换为英文编号 [英] JavaScript - replace to English number

查看:110
本文介绍了JavaScript - 替换为英文编号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将孟加拉语数字替换为英语数字。例如

I want to replace Bengali numbers to English numbers. such as

 var bengali = [০,১,২,৩,৪,৫,৬,৭,৮,৯];
 var eng = [0,1,2,3,4,5,6,7,8,9];

bengali.replace(eng);

这样任何人都可以写任何bengali号码,然后转换为英文号码。我怎样才能实现这个目标?

So that anyone write any bengali number it convert to english number. How can I achieve this?

推荐答案

您有两种选择,具体取决于您希望代码的可维护性。

You have two options, depending on how maintainable you want the code to be.

我建议使用由孟加拉语数字键入的哈希值,并替换为值:

I would recommend using a hash, keyed by Bengali number, and replacing with the value:

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('৯  ৭  ৩');

<pre id=r></pre>

如果由于某种原因,这是不可能的,那么你可以使用两个数组和类似的技术在它们之间进行映射。

If, for some reason, that isn't possible then you can use two arrays and a similar technique to map between them.

这篇关于JavaScript - 替换为英文编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆