Converting whitespace string to url in JavaScript

In web urls if we provide space in the url, the browser automatically replaces all the spaces with the string '%20'

We are required to write a JavaScript function that takes in a string as the first and the only argument. The function should then construct and return a new string in which a whitespace, wherever it was in place, replaced by '%20'

For example −

If the input string is −

const str = 'some extra Space';

Then the output should be −

const output = 'some%20extra%20%20Space';


The code for this will be −

 Live Demo

const str = 'some extra Space';
const replaceWhitespace = (str = '') => {
   let res = '';
   const { length } = str;
   for(let i = 0; i < length; i++){
      const char = str[i];
      if(!(char === ' ')){
         res += char;
         res += '%20';
   return res;


And the output in the console will be −