JavaScript URLify a given string (Replace spaces is %20)
Last Updated :
29 May, 2024
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:
1. 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);
OutputGeeks%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.
2. 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);
OutputGeeks%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.
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);
OutputGeeks%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.
4. 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);
OutputGeeks%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.
5. 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);
OutputGeeks%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.
6. Using replaceAll() Function Approach
In this approach, we use the replaceAll() function in JavaScript, which allows for replacing all occurrences of a specified substring with another substring. This method simplifies the task of URLifying the input string by directly substituting all spaces with the “%20” encoding.
Example: In this example, we are using the replaceAll() function in JavaScript.
JavaScript
// Using replaceAll() function Approach
let inputStr = "Geeks for Geeks";
let outputStr = inputStr.replaceAll(' ', '%20');
console.log(outputStr);
OutputGeeks%20for%20Geeks
Time complexity: O(N), where N is the length of the input string. The replaceAll() function internally iterates over the entire string to replace all occurrences of the specified substring.
Auxiliary space: O(1). The replaceAll() function performs the replacement in-place and does not create additional data structures that depend on the size of the input string.
Similar Reads
Replace all '0' with '5' in an Input Integer using JavaScript
Given a number, our task is to take an input integer and replace all occurrences of the digit '0' with the digit '5'. We can solve this problem by using various methods in JavaScript. Example: Input:n = 1020Output:1525Below are the approaches to replace all '0' with '5' in an input integer using Jav
4 min read
Replace Specific Words in a String Using Regular Expressions in JavaScript
In this article, we are going to learn about replacing specific words with another word in a string using regular expressions. Replacing specific words with another word in a string using regular expressions in JavaScript means searching for all occurrences of a particular word or pattern within the
4 min read
JavaScript - How to Replace Multiple Characters in a String?
Here are the various methods to replace multiple characters in a string in JavaScript.1. Using replace() Method with Regular ExpressionThe replace() method with a regular expression is a simple and efficient way to replace multiple characters.JavaScriptconst s1 = "hello world!"; const s2 = s1.replac
3 min read
JavaScript Program for Generating a String of Specific Length
In this article, we are going to discuss how can we generate a string having a specific length. You might encounter many situations when working with JavaScript where you need to produce a string with a specified length. This could be done for a number of reasons, including generating passwords, uni
4 min read
JavaScript Program to Truncate a String to a Certain Length
In this article, we are going to learn how can we truncate a string to a certain length. Truncating a string to a certain length in JavaScript means shortening a string so that it doesn't exceed a specified maximum length. This can be useful for displaying text in user interfaces, such as titles or
3 min read
How to Extract URLs from a String in JavaScript ?
In this article, we are given a string str which consists of a hyperlink or URL present in it. We need to extract the URL from the string using JavaScript. The URL must be complete and you need to print the entire URL. Example: Input :-str = "Platform for geeks: https://www.geeksforgeeks.org"Output
3 min read
JavaScript Program to Truncate a String to a Certain Length and Add Ellipsis (...)
In this article, we will see how to truncate a string to a certain length and add an ellipsis (...) in JavaScript. To truncate a string to a specific length and add an ellipsis (...) in JavaScript means shortening the string to a predefined character count, indicating that the content continues beyo
3 min read
JavaScript Program to Swap Characters in a String
In this article, We'll explore different approaches, understand the underlying concepts of how to manipulate strings in JavaScript, and perform character swaps efficiently. There are different approaches for swapping characters in a String in JavaScript: Table of Content Using Array ManipulationUsin
6 min read
JavaScript Program to Remove Last Character from the String
In this article, we will learn how to remove the last character from the string in JavaScript. The string is used to represent the sequence of characters. Now, we will remove the last character from this string. Example: Input : Geeks for geeks Output : Geeks for geek Input : Geeksforgeeks Output :
3 min read
JavaScript- Remove Last Characters from JS String
These are the following ways to remove first and last characters from a String:1. Using String slice() MethodThe slice() method returns a part of a string by specifying the start and end indices. To remove the last character, we slice the string from the start (index 0) to the second-to-last charact
2 min read