Open In App

JavaScript URLify a given string (Replace spaces is %20)

Last Updated : 13 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to discuss how can we URLify a given string using JavaScript. In which we will be transforming the spaces within the input strings into the “%20” sequence. The process of URLLification consists of replacing these spaces with the ‘%20’ encoding. This task is essential for creating valid URLs, and query parameters.

Example:

Input: "Geeks for Geeks"
Output: Geeks%20for%20Geeks

These are the following approaches by using these you can get the URLify string:

  • Using Iterations Approach
  • Using the Recursive Function Approach
  • Using ‘split()’, ‘map()’ and ‘join()’ Function Approach
  • Using replace() function Approach
  • Using reduce() function Approach

JavaScript Program to URLify a given String Using Iterations Approach

In this specified approach, we are iterating through each character of the given input string by the user. The function checks characters one by on if there is space or not. If the space is encountered, then it is replaced with the “%20” sequence, else it appends the characters into the output string.

Example: In this example, we’re using the Iterations approach in JavaScript.

Javascript




// Iterations Approach
let inputStr = "Geeks for Geeks";
let outputStr = '';
for (let i = 0; i < inputStr.length; i++) {
    if (inputStr[i] === ' ') {
        outputStr += '%20';
    } else {
        outputStr += inputStr[i];
    }
}
console.log(outputStr);


Output

Geeks%20for%20Geeks

Time complexity: O(N), where N is the length of the string.

Auxiliary space: O(1). The outputStr variable is the only additional space used, and it doesn’t depend on the size of the input string.

JavaScript Program to URLify a given String Using the Recursive Function Approach

In this approach, we are using the recursive function approach in which the function checks the character of the input string one by one. If the space is been encountered, then the function appends “%20” with the output string. The function continues this task, moving through the string recursively till all the characters from the string are been processed.

Syntax:

function functionName(/* parameters */) {
if (/* base case condition */) {
// Return some value or perform an action
}
}

Example: In this example, we are using the recursive function in JavaScript.

Javascript




// Using Recursive Function
function urlifyRecursiveFunc(str) {
    if (str.length === 0) {
        return '';
    }
    if (str[0] === ' ') {
        return '%20' + urlifyRecursiveFunc(str.slice(1));
    }
    return str[0] + urlifyRecursiveFunc(str.slice(1));
}
  
let inputStr = "Geeks for Geeks";
let outputStr = urlifyRecursiveFunc(inputStr);
console.log(outputStr);


Output

Geeks%20for%20Geeks

Time complexity: O(N), where N is the length of the string.

Auxiliary space: O(N), where N is the length of the input string. This is because the recursive function apporache creates a new stack frame for each character in the input string, and each stack frame holds a portion of the output string.

JavaScript Program to URLify a given String Using split() map() and join() Function Approach

In this approach, we are using the split()‘, ‘map()‘, and join() functions to replace the spaces with “%20” encoding. Firstly, the input string is been split into an array of characters, By using the map() function we iterate through each character and replace the spaces with the “%20” and other characters are unchanged. After replacing, the array is rejoined into the single output string by using the ‘join()’ function.

Example: In this example, we are using the ‘split()’, ‘map()’, and ‘join()’ functions in JavaScript.

Javascript




//Using split(), map() and join() functions
let inputStr = "Geeks for Geeks";
let outputStr = inputStr
      .split('')
      .map(char => (char === ' ' ? '%20' : char))
      .join('');
console.log(outputStr);


Output

Geeks%20for%20Geeks

Time complexity: O(N), where N is the length of the string.

Auxiliary space: O(N), where N is the length of the input string. This is because the split() function used in the apporach creates an array of characters, and the join() function creates a new string.

JavaScript Program to URLify a given String Using replace() function Approach

In this simple approach, we are using the replace() function in JavaScript. This function uses the regular expression (‘/ /g’). The ‘g‘ flag used here assures that all occurrences of spaces are properly replaced with the “%20” encoding sequences throughout the entire string.

Example: In this example, we are using the replace() function in JavaScript.

Javascript




// Replace function in JavaScript
let inputStr = "Geeks for Geeks";
let outputStr = inputStr.replace(/ /g, '%20');
console.log(outputStr);


Output

Geeks%20for%20Geeks

Time complexity: O(N), where N is the length of the input string.

Auxiliary space: O(1). The replace() function works in-place on the input string and does not create any additional data structures that depend on the size of the input string.

JavaScript Program to URLify a given String Using reduce() function Approach

In this approach, we will be using the ‘reduce() function to URLify the inputted string. Firstly, we will start by splitting the input string into the array of characters, Then we will use the reduce() function to iterate through the array, by accumulating the URLified string character by character. For the individual character in the array, we will check its space, in which case we append “%20” or we will append the character as it is.

Example: In this example, we are using the reduce() function in JavaScript.

Javascript




// Using reduce() function Approach
let inputStr = "Geeks for Geeks";
let outputStr = inputStr.split('')
    .reduce((result, char) => {
    if (char === ' ') {
        return result + '%20';
    } else {
        return result + char;
    }
}, '');
console.log(outputStr);


Output

Geeks%20for%20Geeks

Time complexity: O(N), where N is the length of the input string.

Auxiliary space: O(N), where N is the length of the input string. The split(”) function creates an array of characters, and the reduce() function creates and maintains the result string. The space used for these data structures is directly proportional to the length of the input string.



Like Article
Suggest improvement
Next
Share your thoughts in the comments

Similar Reads