Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Full-width Numbers convert to half-width Numbers in jQuery / JS [closed]

A would like to convert Full-width Numbers (e.g. 123) to half-width Numbers (e.g. 123). I found code do this in PHP but not in JS. Could anyone helps? Thanks.

function fullWidthNumConvert(fullWidthNum){
    // Magic here....
    ....
    return halfWidthNum;
}
like image 756
Kenneth Yau Avatar asked Mar 21 '17 02:03

Kenneth Yau


People also ask

How do you convert half-width to full width?

Half and full width characters differ by 65248. So all you need to do is simply add that number to each character.

How do you use half-width?

For Windows: Use F10 within an online form to toggle quickly between full-width and half-width characters. For Mac users: Full-width, zenkaku katakana, is control + k. Half-width, hankaku kana, is control + ;.

What is half-width alphanumeric?

Half-width refers to characters where the horizontal and vertical length ratio is 1:2. These characters are horizontally narrow. English letters, numbers, spaces, and punctuation marks such as comma and period are half-width by default.

What is a half size number?

half size in American English noun. any size in women's garments designated by a fractional number from 121⁄2 through 241⁄2, designed for a short-waisted, full figure.


1 Answers

Do a string .replace(), using a regular expression to match the characters in question. The callback in .replace()'s second argument can get the character code of the matched character and subtract from that to get the character code of the standard digit, then convert that back to a string.

function fullWidthNumConvert(fullWidthNum){
    return fullWidthNum.replace(/[\uFF10-\uFF19]/g, function(m) {
      return String.fromCharCode(m.charCodeAt(0) - 0xfee0);
    });
}


console.log(fullWidthNumConvert("0123456789"));
console.log(fullWidthNumConvert("Or in the middle of other text: 123. Thank you."));
like image 113
nnnnnn Avatar answered Oct 13 '22 02:10

nnnnnn