我正在尝试创建一个 javascript 程序,在其中我用 %20 替换字符串中的所有空格,而不使用替换函数。当我尝试运行我的程序时出现错误。不知道出了什么问题。
let urlEncode = function(text) {
text = text.trim();
let newstring;
for (let i = 0; i < text.length; i++) {
if (text[i] == " ") {
newstring[i] = "%20";
} else {
newstring[i] = text[i];
}
}
return newstring;
};
console.log(urlEncode("blue is greener than purple for sure"));Run Code Online (Sandbox Code Playgroud)
字符串是不可变的——你不能分配给它们的索引。相反,初始化newstring为空字符串,用于+=将现有字符串与新字符连接起来:
let urlEncode = function(text) {
text = text.trim();
let newstring = '';
for (const char of text) {
newstring += char === ' '? '%20' : char;
}
return newstring;
};
console.log(urlEncode("blue is greener than purple for sure"));Run Code Online (Sandbox Code Playgroud)
或者,不要重新发明轮子,并使用encodeURIComponent:
console.log(encodeURIComponent("blue is greener than purple for sure"));Run Code Online (Sandbox Code Playgroud)