Published on

How to Get Last Part of Path or URL Using JavaScript

Authors

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