Not long ago to Ali's online written test, the last question can be regarded as baffled me, the topic is probably like this: with the native JS implementation of the character string in the English alphabet characters and the recognition of Chinese characters in accordance with two units, English and characters in accordance with a unit calculation, at first, I do not know what good way to write C code too much Just use C code to ASCII method, written by the end of the character to know, JS is very tall on the gadget, this trick does not work. Here I introduce a very simple and reliable method, using the Unicode character set approach to solve.
First, the brain. Tip: The Unicode character set number 0-128 is the category of the English alphabetic character (half-width), outside of which is the other character (full-width), with the JS string charCodeAt () can return the processed character Unicode code.
Below is the function method I designed
Function strchange (str,n) { //str is the string to be passed in, N is the length of the string that needs to be returned var mystr = null; //a new string to hold the string to return var k = 0; for (var i=0;i<str.length;i++) { if (Str.charcodeat (i) >=0&&str.charcodeat (i) <128) { //charcodeat (i) can return Unicode code length after character processing if (k==n) break; //if offerings, jump out of the loop mystr=mystr+str.charat (i); //the character into the string to be returned k+=1; } else{ if (K==n) break; mystr=mystr+str.charat (i); k+=2; } } return mystr; //returns the truncated string}
This article from "D Tune small snail" blog, declined reprint!
Use JS to identify the alphabetic characters and non-characters (kanji) in a string