JavaScript: Join all given URL segments together, then normalizes the resulting URL
JavaScript fundamental (ES6 Syntax): Exercise-55 with Solution
Write a JavaScript program to join all given URL segments together, then normalize the resulting URL.
- Use String.prototype.join('/') to combine URL segments.
- Use a series of String.prototype.replace() calls with various regexps to normalize the resulting URL (remove double slashes, add proper slashes for protocol, remove slashes before parameters, combine parameters with '&' and normalize first parameter delimiter).
Sample Solution:
JavaScript Code:
//#Source https://bit.ly/2neWfJ2
const URL_Join = (...args) =>
args
.join('/')
.replace(/[\/]+/g, '/')
.replace(/^(.+):\//, '$1://')
.replace(/^file:/, 'file:/')
.replace(/\/(\?|&|#[^!])/g, '$1')
.replace(/\?/g, '&')
.replace('&', '?');
console.log(URL_Join('http://www.google.com', 'a', '/b/cd', '?foo=123', '?bar=foo'));
Sample Output:
http://www.google.com/a/b/cd?foo=123&bar=foo
Pictorial Presentation:
Flowchart:

Live Demo:
See the Pen javascript-basic-exercise-55-1 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Write a JavaScript program to initialize an array containing the numbers in the specified range where start and end are inclusive with their common difference step.
Next: Write a JavaScript program to check if all elements in a given array are equal or not.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join