Use JS to identify the alphabetic characters and non-characters (kanji) in a string

Source: Internet
Author: User
Tags alphabetic character

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.