Reputation: 1
urlEncode = function(text) {
let str = text.split(' ').join('%20');
return str;
};
The above is working but If a string has a space in the beginning or end it should not replace %20 .The above is replacing every space .I tried using loops ..
for(let i = 1 ;i < text.length-1;i++){
if(text[i]===''){
text[i]='%20';
}
}
return text;
this one is returning the original text with no change.
Upvotes: 0
Views: 347
Reputation: 1
or, you can test another
const urlEncode = text => text.replace(/[^\s]\s[^\s$]/g, '%20')
Upvotes: 0
Reputation: 371019
A regular expression to match a space not at the beginning nor end of the string would work.
const urlEncode = text => text.replace(/(?!^) (?!$)/g, '%20');
(?!^)
- not at the beginning(?!$)
- not at the endAnother method would be to turn the text string into an array so that assignment to its indicies using your second snippet would work. Replace the indicies as needed, then join into a string again and return.
Upvotes: 1