How to use the Recursive Function Approach In Javascript
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.
// 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 URLify a given string (Replace spaces is %20)
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:
Table of Content
- Using Iterations Approach
- Using the Recursive Function Approach
- Using split() map() and join() Function Approach
- Using replace() function Approach
- Using reduce() function Approach
- Using replaceAll() Function Approach