Fatuma Said
Fatuma Said

Reputation: 1

code to replace all spaces except the first and last with %20

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

Answers (2)

Jason.Kwo
Jason.Kwo

Reputation: 1

or, you can test another

const urlEncode = text => text.replace(/[^\s]\s[^\s$]/g, '%20')

Upvotes: 0

CertainPerformance
CertainPerformance

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 end

Another 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

Related Questions