[英]How do I replace a string without using the replace function in javascript?
I'm trying to create a javascript program where I replace all spaces in a string with %20 without using the replace function.我正在尝试创建一个 javascript 程序,在其中我用 %20 替换字符串中的所有空格,而不使用替换函数。 I'm getting an error when I try to run my program.
当我尝试运行我的程序时出现错误。 Not sure what's wrong.
不知道出了什么问题。
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"));
Strings are immutable - you can't assign to their indicies.字符串是不可变的——你不能分配给它们的索引。 Rather, initialize
newstring
to the empty string, use +=
to concatenate the existing string with the new character(s):相反,将
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"));
Or, don't reinvent the wheel, and use encodeURIComponent
:或者,不要重新发明轮子,而使用
encodeURIComponent
:
console.log(encodeURIComponent("blue is greener than purple for sure"));
You can use combination of split
and join
to achieve in simplified way.您可以使用
split
和join
组合以简化的方式实现。
let urlEncode = function(text) { return text .trim() .split(" ") .join("%20"); }; console.log(urlEncode("blue is greener than purple for sure"));
Your Error Is first you must set newstring
in first let
only create your variable but not assign any value to it then newstring[0]
is undefined
then you get error i use +=
for add char to string and it is better你的错误是必须首先设置
newstring
在第一let
只有创建变量,但没有任何值分配给它,然后newstring[0]
是undefined
,那么你得到的错误,我使用+=
为附加字符字符串,这是更好
you can change your Code Like this你可以像这样改变你的代码
let urlEncode = function(text) { text = text.trim(); let newstring=""; for (let i = 0; i < text.length; i++) { if (text[i] == " ") { newstring+= "%20"; } else { newstring+= text[i]; } } return newstring; }; console.log(urlEncode("blue is greener than purple for sure"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.