Above code works in most cases, however there is a catch when working with words to find a ranking based on above code. For example, aa would give a ranking of 97+97 = 194 (actual would be 1+1 = 2) whereas w would give 119 (actual would be 23) which makes aa > w.To fix this subtract 96 from above result, to start he positioning from 1.
function ascii_code (character) {
// Get the decimal codelet code = character.charCodeAt(0);
// If the code is 0-127 (which are the ASCII codes,if (code < 128) {
// Return the code obtained.return code;
// If the code is 128 or greater (which are expanded Unicode characters),}else{
// Return -1 so the user knows this isn't an ASCII character.return -1;};};
如果您正在寻找字符串中的只有 ASCII字符(例如,延迟字符串),您可以这样做:
function ascii_out (str) {// Takes a string and removes non-ASCII characters.
// For each character in the string,for (let i=0; i < str.length; i++) {
// If the character is outside the first 128 characters (which are the ASCII// characters),if (str.charCodeAt(i) > 127) {
// Remove this character and all others like it.str = str.replace(new RegExp(str[i],"g"),'');
// Decrement the index, since you just removed the character you were on.i--;};};return str};