admin管理员组文章数量:1394740
I'm trying to create a javascript program where I replace all spaces in a string with %20 without using the replace function. 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"));
I'm trying to create a javascript program where I replace all spaces in a string with %20 without using the replace function. 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"));
Share
Improve this question
edited Jan 27, 2020 at 7:25
CertainPerformance
372k55 gold badges352 silver badges357 bronze badges
asked Jan 27, 2020 at 4:27
AbcAbc
431 silver badge8 bronze badges
1
- 1 what error are you getting exactly? – Prateek Commented Jan 27, 2020 at 4:29
3 Answers
Reset to default 7Strings 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):
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
:
console.log(encodeURIComponent("blue is greener than purple for sure"));
You can use bination of split
and join
to achieve in simplified way.
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
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"));
本文标签: How do I replace a string without using the replace function in javascriptStack Overflow
版权声明:本文标题:How do I replace a string without using the replace function in javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744104566a2591006.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论