使用 ASCII 代码格式化字符串和删除特殊字符不起作用 (JavaScript)

Format string and deleting special characters using ASCII code doesn't work (JavaScript)

我正在尝试使用 ASCII 代码格式化任何给定的字符串以供参考。该格式必须删除除数字、“-”或“_”和空格之外的任何特殊字符。这是代码:

 function FormatString(sentence) {
        result = new String();
        j = 0;
        sentence = sentence.toUpperCase();
        i = 0;

        while(i < sentence.length) {
            if (
                (sentence[i]>=65 && sentence[i]<=90) ||
                (sentence[i]>=48 && sentence[j]<=57) ||
                sentence[i]==32 || sentence[i]==45
            ) {
                sentence[j] = result[i];
                j = j + 1;
            }
            i = i + 1;
        }
        return result;
    }

然后调用函数

console.log(FormatString('No running in the hallways!!!'))

输出应该是“走廊里没有 运行”

也许 string.replace 使用正则表达式可以帮助您:

const regex = /[-_]/g
"afasf-afsaf_fafa".replace(regex,''); //"afasfafsaffafa"

假设使用 Regular Expressions 是解决您问题的最佳方法,我假设您想使用 ASCII 比较是有原因的。

以下解决方案有效:

function FormatString (sentence) {
    let result = "";

    const uppercaseSentence = sentence.toUpperCase();

    for (let i=0; i<uppercaseSentence.length; i++) {
        let cc = uppercaseSentence.charCodeAt(i);
        if ((cc>=65 && cc<=90) || (cc>=48 && cc<=57) || cc==32 || cc==45) {
            result += sentence[i];
        }
    }

    return result;
}

我在你的函数下面报告并评论它有什么问题:

function FormatString(sentence) {
    
    // you are declaring a global variable here.
    // let result = ... or var result = ... makes it local
    // In javascript you can use an string literal `""` in place of new String()
    result = new String();
    
    // again a global variable
    j = 0;
    
    // you are chaning the passed parameter to an uppercase string
    // you lost the original string now
    sentence = sentence.toUpperCase();
    
    // again a global variable
    i = 0;

    // nothing wron with the while loop, only the for loop is more concise in
    // this case
    while(i < sentence.length) {
        
        if (
            // sentence[i] is a streing with length 1 and it returns false if
            // compared with a number. Use instead sentence.charCodeAt(i) which
            // returns the ASCII code of the i-th character
            (sentence[i]>=65 && sentence[i]<=90) ||
                                // there is a j here in place of an i
            (sentence[i]>=48 && sentence[j]<=57) ||
            sentence[i]==32 || sentence[i]==45
        ) {
            // you can't assign single characters in javascript
            // what you want to do is result += sentence[i],
            // but remember that sentence is now all uppercase and so will be 
            // result!
            sentence[j] = result[i];
            j = j + 1;
        }
        i = i + 1;
    }
    
    return result;
}