目前这是我的代码。
function clean_string(raw_string) {
A =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 1234567890".split(
""
);
var cleaned_string = raw_string.toLowerCase();
for (i = 0; i < cleaned_string.length; i++) {
if (!A.includes(cleaned_string[i])) {
cleaned_string = setCharAt(cleaned_string, i, " ");
}
}
cleaned_string = cleaned_string.replace(/\s\s+/g, " ");
return cleaned_string;
}
function setCharAt(str, index, chr) {
if (index > str.length - 1) return str;
return str.substring(0, index) + chr + str.substring(index + 1);
}
我不懂正则表达式,但使用正则表达式可能会更容易。这是我想做的事情:
输入:
Hello, David World 123!
输出:hello david world 123
基本上我想做的是将除a-z0-9以外的任何字符替换为一个空格,然后删除多余的空格,也就是说,我只想在结果中得到a-z0-9。如何做到呢?注:代码可以运行,但我认为它看起来很糟糕而且效率不高。
编辑:抱歉,我的意思是我只想在输出中得到小写字母。我太蠢了。