0

I have a URL as follows http://localhost:8080/list/PEPPR_BDCAREUGWJ

I need "PEPPR_BDCAREUGWJ" from this url. How to do this by javascript?

devbeans
  • 99
  • 1
  • 10
  • take a look nodejs and url-module – doğukan Apr 21 '19 at 14:58
  • 2
    Possible duplicate of [Last segment of URL](https://stackoverflow.com/questions/4758103/last-segment-of-url) – Remco Bravenboer Apr 21 '19 at 15:00
  • Possible duplicate of [How do I parse a URL into hostname and path in javascript?](https://stackoverflow.com/questions/736513/how-do-i-parse-a-url-into-hostname-and-path-in-javascript) – weegee Apr 21 '19 at 15:12

2 Answers2

1

You can use split() and get the last value from array.

let str = 'http://localhost:8080/list/PEPPR_BDCAREUGWJ'
let res = str.split('/').pop()

console.log(res)

Another way can be using lastIndexOf() and slice()

let str = 'http://localhost:8080/list/PEPPR_BDCAREUGWJ'
let res = str.slice(str.lastIndexOf('/')+1)

console.log(res)

You can also use regular expression.

let str = 'http://localhost:8080/list/PEPPR_BDCAREUGWJ'
let res = /\/[^\/]+$/.exec(str)[0].slice(1)

console.log(res)
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
1

Just split by slash(/) using String#split method and get last part from the array using Array#pop method.

let str = 'http://localhost:8080/list/PEPPR_BDCAREUGWJ'
let res = str.split('/').pop();

console.log(res)
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188