0

There are so many ways to extract data from a string whether it be substring, split, etc. This is an open ended question and may be too open ended, but is there a "right" way to do this? For example I have a URL http://myServer:8000/courses/courseName/courseID what is the right way to extract out courseID in this instance?

This is an example of what I have done:

const test2 = test.split('/courses/').slice(1).toString();
const test3 = test2.substring(0, test2.lastIndexOf('/'))
console.log(test3)
programmerGuy
  • 137
  • 3
  • 11
  • If it's a url search parameter, there's an *proper* way to get it using [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams). But if it's a part of url path, you may get the pathname using `new URL('your url').pathname` first and then you're free to use anything as long as it's consistent. – Hao Wu Aug 23 '23 at 02:08

1 Answers1

0

The following piece of code can help you get the last part of the URL in a single line using Javascript. This will work if the CourseID is always the last element of the URL. I am not sure how fast is it but definitely, it is elegant

url.substr(url.lastIndexOf('/') + 1)
Rinsad Ahmed
  • 1,877
  • 1
  • 10
  • 28