How to URLify a string in JavaScript

Here is one way to URLIfy a string (replacing ‘ ‘ with ‘%20’).
Time complexity: O(n)
Space complexity: O(n) where n is the number of characters in the string. An additional factor could include the number of spaces in the string.

We can assume that there is enough space to hold the extra ‘%20’ in memory.
Note: JavaScript Strings are immutable objects and cannot be modified in place.

urlifyTry in REPL
1
2
3
function URLify(string) {
return string.trim().replace(/\s/g, '%20');
}

Tests can be found at REPL.it