How to Get Last Part of Path or URL Using JavaScript

July 26, 2020

Using Regex

const url = '/blog/2019/07/hello-nesin-technologies-llp/'
url.match(/([^\/]*)\/*$/)[1]
// → hello-nesin-technologies-llp

Using array split() method

const url = '/blog/2019/07/hello-nesin-technologies-llp/'

// filter is used to remove empty item in array
const segements = url.split('/').filter(segment => segment) 
const lastSegment = segements[segements.length-1]

// → hello-nesin-technologies-llp

Reference


👋 I'm Ashik Nesin • Sr. Frontend Engineer @Chargebee 👨‍💻• I write about modern Javascript & building web apps

© 2021 Nesin Technologies LLP