URL Parsing

node v10.24.1
version: 1.0.0
endpointsharetweet
URLs are versatile but easy to generate incorrectly, especially when combined from various sources. Fortunately, there are libraries that not only build URLs from their separate parts - scheme, domain, etc. - but also parse and clean badly-formatted ones. Take this example, with extra forward slashes and an unnecessary WWW subdomain:
const normalizeUrl = require("normalize-url") const fixedUrl = normalizeUrl("https://www.duckduckgo.com//?q=meme&t=h_&df=d") "https://duckduckgo.com/?df=d&q=meme&t=h_" === fixedUrl
Note that normalize-url also orders the parameters, which can make them a little easier to understand.
fixedUrl
You can call the endpoint of this RunKit with an encoded URL parameter to test this library. Open Developer Tools and run `copy(encodeURIComponent("https://www.duckduckgo.com//?q=meme&t=h_&df=d"))`, then paste into the URL in the form `<RunKitURL>?url=<paste>`.
const url = require("url") exports.endpoint = (request, response) => { const query = url.parse(request.url, true).query const queryUrl = decodeURIComponent(query.url) const normalizedUrl = normalizeUrl(queryUrl) response.setHeader("Content-Type", "text/plain") response.end(normalizedUrl) }
Loading…

no comments

    sign in to comment