w3resource

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:

JavaScript Fundamental: Join all given URL segments together, then normalizes the resulting URL

Flowchart:

flowchart: Join all given URL segments together, then normalizes the resulting URL

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.



Follow us on Facebook and Twitter for latest update.