- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Converting whitespace string to url in JavaScript
In web urls if we provide space in the url, the browser automatically replaces all the spaces with the string '%20'
We are required to write a JavaScript function that takes in a string as the first and the only argument. The function should then construct and return a new string in which a whitespace, wherever it was in place, replaced by '%20'
For example −
If the input string is −
const str = 'some extra Space';
Then the output should be −
const output = 'some%20extra%20%20Space';
Example
The code for this will be −
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));
Output
And the output in the console will be −
some%20extra%20%20Space
Advertisements