Converting whitespace string to url in JavaScript

In web URLs, browsers automatically replace spaces with '%20' for proper encoding. JavaScript provides multiple methods to convert whitespace characters to URL-encoded format.

We need to write a function that takes a string and replaces all whitespace characters with '%20'.

For example, if the input string is:

const str = 'some extra Space';

Then the output should be:

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

Using Manual Loop Method

This approach iterates through each character and manually replaces spaces:

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));
some%20extra%20%20Space

Using String.replace() Method

A simpler approach using the built-in replace method with regular expressions:

const str = 'some extra Space';
const replaceWithReplace = (str) => {
    return str.replace(/ /g, '%20');
};
console.log(replaceWithReplace(str));
some%20extra%20%20Space

Using encodeURIComponent() (Recommended)

The most robust approach using JavaScript's built-in URL encoding function:

const str = 'some extra Space with special chars!@#';
const encodeUrl = (str) => {
    return encodeURIComponent(str);
};
console.log(encodeUrl(str));
some%20extra%20%20Space%20with%20special%20chars!%40%23

Comparison

Method Handles Special Characters Performance Recommended
Manual Loop No Slow No
String.replace() Only spaces Good For spaces only
encodeURIComponent() Yes Best Yes

Conclusion

Use `encodeURIComponent()` for complete URL encoding or `String.replace()` for simple space replacement. The manual loop approach should be avoided for performance reasons.

Updated on: 2026-03-15T23:19:00+05:30

715 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements