let’s say we have such url:
const a = 'https://www.example.com/media/english/exaProns/p008-001600778.mp3?version=1.2.60'
How can we extract the name of the track like:
p008-001600778.mp3
I splited the url twice . one with / and one with ?. but there should be a better solution.
4
Answers
If you want to get it consistently without too much bother, you could use the
URL
constructor and then let it extract thepathname
. After that, simply split on the/
and pop out the last one:The
URL
constructor just gives you an easier breakdown of the actual URL, allowing you to manipulate it in the same way the browser does.I would recommend using
URL#pathname
to remove all the extra parts after the?
safely and then you can use regex to remove everything before the last/
The reason I haven’t used a single large regex is because
?
in the pathnameIf your url’s structure is the same and only track name changes, you can use this
regex
pattern:It extracts the part between last
/
and?
something like this:
In JavaScript, you can use the URL API to parse the URL and then extract the pathname. This will give you the path section of the URL, which follows the domain part up to the first ‘?’ or ‘#’ character. You can then split the pathname by ‘/’ and get the last element to get the file name.
Here’s an example:
In this code:
We first create a URL object from the string a. This object allows us to easily extract different parts of the URL.
We then get the pathname of the URL, which is the part of the URL from the domain to the first ‘?’ or ‘#’ character.
Next, we split this pathname into its individual parts, using ‘/’ as the separator. This gives us an array of strings.
Finally, we get the last element from this array, which is the file name.