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"));