3

I have a web page (charset=UTF-8) with several fields, and a client-side JavaScript program. One particular input field is supposed to contain a number, which is processed by a JavaScript function. The web page is supposed to be used by Japanese people, in addition to German ones.

When Japanese are using the form, they will likely use a Japanese input method for entering the data. This means that in particular a number such as "1" will be entered as "Japanese Number 1", which is the unicode character FULLWIDTH DIGIT ONE, i.e. %uFF11. I would like to turn such a number into a numeric value in JavaScript?

Here is how far I came. I focus in this example only on the digit 1, because if I can handle this, I can handle all digits:

The content of the input field is stored in my JavaScript variable moneystr. My idea is to replace every occurance of a Japanese digit 1 by a "normal" digit 1. I found that I can do this for example like this:

moneystr=moneystr.replace(/\uFF11/g,'1');

This seems to work well.

For extending this idea to all digits, I can either write down 10 such replacement statements, or write a loop from 0 to 9 and calculate the unicode regexp from the loop vaiable.

However, both solutions look like bad programming style to me. Is there a more concise way to do this? If I would write this in Perl, I would use the tr operator, where I can translate everything in one go. Is a similar feature available in JavaScript too? Or should I use a completely different approach?

user1934428
  • 19,864
  • 7
  • 42
  • 87
  • 1
    possible duplicate of [How do you map-replace characters in Javascript similar to the 'tr' function in Perl?](http://stackoverflow.com/questions/10726638/how-do-you-map-replace-characters-in-javascript-similar-to-the-tr-function-in) – Stephan Feb 08 '14 at 03:54
  • 1
    Try this elegant solution instead: http://stackoverflow.com/a/10726800/363573 – Stephan Feb 08 '14 at 03:54
  • Thanks. This (in particular, the emulation of Perl's tr function) solved my problem! – user1934428 Feb 10 '14 at 15:36

1 Answers1

1

Here is my solution:

I used the function tr() shown in Alex' link (https://stackoverflow.com/a/10727555) and used the following code to translate my string:

    moneystr = tr(moneystr, "0123456789 ", "0123456789 ");
HiEv
  • 88
  • 7
user1934428
  • 19,864
  • 7
  • 42
  • 87