How can I parse a url?
site.com:8080/someFile.txt?attr=100
or
site.com:8080/someFile.txt/?attr=100
I need to get someFile.txt
, where is a file name I set by myself as the format (txt or some other).
UPDATE
I tried
var path = url.parse(req.url).path;
But I still cannot get the path (someFile.txt
).
The filename is the last part of the URL from the last trailing slash. For example, if the URL is http://www.example.com/dir/file.html then file. html is the file name.
The path. basename() method returns the filename part of a file path.
To get the absolute path of the current file/code. To get the name of the file currently executing.
Something like this..
var url = require("url"); var path = require("path"); var parsed = url.parse("http://example.com:8080/test/someFile.txt/?attr=100"); console.log(path.basename(parsed.pathname));
here's my working code, hope it helps
import path from 'path' const getBasenameFormUrl = (urlStr) => { const url = new URL(urlStr) return path.basename(url.pathname) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With