Home>Article>Web Front-end> JS full-width and half-width conversion examples
Recently I am doing a form verification on a PC website page, and I need to convert full-width input into half-width symbols. I have not learned about these coding knowledge before, so I still have to Google to look up the information, so I will briefly summarize it.
1. What are full-width and half-width?
Full-width: It is a kind of computer character, which means that one full-width character occupies the position of two standard characters (or two half-width characters). Full width occupies two bytes.
Chinese characters, English characters that specify full-width, and graphic symbols and special characters in the national standard GB2312-80 are all full-width characters. In full-width, letters and numbers occupy equal-width positions like Chinese characters.
Half-width: refers to a character occupying a standard character position. Half-width occupies one byte.
Half-width characters are ASCII characters. When no Chinese character input method works, the letters, numbers and characters entered are all half-width characters.
Each half-width character only occupies one byte of space (one byte has 8 bits, a total of 256 encoding spaces). The font size of hieroglyphic languages such as Chinese, Japanese, and Korean is much larger than 256 encoding spaces, so two bytes are used for storage. At the same time, due to the writing habits of hieroglyphics such as China, Japan, and Korea, if full-width characters are used uniformly, the arrangement will appear neat.
For neat arrangement, English and other Latin characters and punctuation are also provided in full-width format.
2. The difference between full-width and half-width
Full-width and half-width are mainly for punctuation marks. Full-width punctuation occupies two bytes, and half-width punctuation occupies one byte. Regardless of whether it is half-width or full-width, Chinese characters take up two bytes.
function ToCDB(str) { var tmp = ""; for (var i = 0; i < str.length; i++) { if (str.charCodeAt(i) > 65248 && str.charCodeAt(i) < 65375) { tmp += String.fromCharCode(str.charCodeAt(i) - 65248); } else { tmp += String.fromCharCode(str.charCodeAt(i)); } } return tmp }
function ToDBC(txtstring) {var tmp = ""; for (var i = 0; i < txtstring.length; i++) { if (txtstring.charCodeAt(i) == 32) {tmp = tmp + String.fromCharCode(12288);} if (txtstring.charCodeAt(i) < 127) { tmp = tmp + String.fromCharCode(txtstring.charCodeAt(i) + 65248); } }return tmp; }
The above is the detailed content of JS full-width and half-width conversion examples. For more information, please follow other related articles on the PHP Chinese website!