# Converting whitespace string to url in JavaScript

JavascriptWeb DevelopmentFront End Technology

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';

## Example

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;
}else{
res += '%20';
};
};
return res;
};
console.log(replaceWhitespace(str));

## Output

And the output in the console will be −

some%20extra%20%20Space
Published on 27-Feb-2021 05:35:36