【发布时间】:2021-07-06 16:28:22
【问题描述】:
我正在尝试使用 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!!!'))
输出应该是“不要在走廊里跑步”
【问题讨论】:
-
起初,
sentence仍然包含字符,而不是代码点,而且字符串是不可变的,您不能更改字符串中的单个字符。看看RegExps,它们是您完成任务所需要的。 -
@Teemu 我想我明白你的意思,那么,我应该改变或做什么?
-
sentence[j] = result[i];这似乎倒退了。result += sentence[j]?如果您有sentence[j]<=57,也可以在其中sentence[i]<=57应该是。 -
@James 它仍然返回一个空字符串,即使很难我将格式化的句子分配给结果变量
标签: javascript string format frontend ascii