【发布时间】:2022-01-06 04:37:13
【问题描述】:
目前,这是我的代码。
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
.
输入:hELlo., <>;dAVId world .;- 123
输出:hello david world 123
.
输入: He.llo David, w!orld 123#
输出:he llo david w orld 123
.
基本上我想要做的是用空格替换除 a-z0-9 之外的任何内容,然后删除双空格。换句话说,我的结果中只需要 a-z0-9。我该怎么做?
附:该代码有效,但我认为它看起来很糟糕而且效率很低。
编辑:对不起,我的意思是我的输出中只需要小写字母。我很笨。
【问题讨论】:
-
您说您希望在输出中允许使用大写字母,但是,在所有提供的示例中,大写字符都替换为小写字符。你能澄清一下吗?
-
@fubar 抱歉,我很笨。我解决了我的问题。我只想要小写字母。谢谢!
标签: javascript regex string trim