Split a URL in JavaScript after every forward slash?

To split a URL in JavaScript, use the split() method with a forward slash (/) as the delimiter. This breaks the URL into an array of segments.

Syntax

url.split("/")

Basic Example

var newURL = "http://www.example.com/index.html/homePage/aboutus/";
console.log("Original URL:", newURL);

var splitURL = newURL.split("/");
console.log("Split URL:", splitURL);
Original URL: http://www.example.com/index.html/homePage/aboutus/
Split URL: [
  'http:',
  '',
  'www.example.com',
  'index.html',
  'homePage',
  'aboutus',
  ''
]

Understanding the Output

The result contains empty strings because:

  • Index 0: 'http:' - the protocol
  • Index 1: '' - empty string between ://
  • Index 2: 'www.example.com' - the domain
  • Index 3-5: Path segments
  • Index 6: '' - empty string from trailing slash

Filtering Out Empty Segments

var url = "https://www.tutorialspoint.com/javascript/arrays/methods";
var segments = url.split("/").filter(segment => segment !== "");

console.log("Clean segments:", segments);
console.log("Domain:", segments[1]);
console.log("Path parts:", segments.slice(2));
Clean segments: [ 'https:', 'www.tutorialspoint.com', 'javascript', 'arrays', 'methods' ]
Domain: www.tutorialspoint.com
Path parts: [ 'javascript', 'arrays', 'methods' ]

Extracting Specific Parts

var url = "https://api.example.com/v1/users/123/profile";
var parts = url.split("/");

console.log("Protocol:", parts[0]);
console.log("Domain:", parts[2]);
console.log("API version:", parts[3]);
console.log("Resource:", parts[4]);
console.log("ID:", parts[5]);
Protocol: https:
Domain: api.example.com
API version: v1
Resource: users
ID: 123

Conclusion

Use split("/") to break URLs into segments. Filter empty strings for cleaner results, and access array indices to extract specific URL components like domain, path, or parameters.

Updated on: 2026-03-15T23:18:59+05:30

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements