Join URL Segments

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to join URL segments and normalize the resulting URL using JavaScript. The lab will guide you through the process of using various regular expressions to remove double slashes, add proper slashes for the protocol, remove slashes before parameters, combine parameters with '&', and normalize the first parameter delimiter. By the end of this lab, you will be able to efficiently join and normalize URL segments using JavaScript.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28456{{"`Join URL Segments`"}} javascript/data_types -.-> lab-28456{{"`Join URL Segments`"}} javascript/arith_ops -.-> lab-28456{{"`Join URL Segments`"}} javascript/comp_ops -.-> lab-28456{{"`Join URL Segments`"}} javascript/spread_rest -.-> lab-28456{{"`Join URL Segments`"}} end

URL Segments Joining and Normalization

To join given URL segments together and normalize the resulting URL, follow the steps below:

  1. Use Array.prototype.join() to combine URL segments.
  2. Use a series of String.prototype.replace() calls with various regular expressions to normalize the resulting URL by:
    • Removing double slashes
    • Adding proper slashes for the protocol
    • Removing slashes before parameters
    • Combining parameters with '&' and normalizing the first parameter delimiter.

Use the code snippet below to join and normalize URL segments:

const URLJoin = (...args) =>
  args
    .join("/")
    .replace(/[\/]+/g, "/")
    .replace(/^(.+):\//, "$1://")
    .replace(/^file:/, "file:/")
    .replace(/\/(\?|&|#[^!])/g, "$1")
    .replace(/\?/g, "&")
    .replace("&", "?");

Example usage:

URLJoin("http://www.google.com", "a", "/b/cd", "?foo=123", "?bar=foo");
// 'http://www.google.com/a/b/cd?foo=123&bar=foo'

Summary

Congratulations! You have completed the Join URL Segments lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like