PHP's parse_url in JavaScript
How to use
You you can install via yarn add locutus
and
require this function via const parse_url = require('locutus/php/url/parse_url')
.
It is important to use a bundler that supports tree-shaking so that you only ship the functions that you actually use to your browser, instead of all of Locutus, which is massive. Examples are: Parcel, webpack, or rollup.js. For server-side use this is typically less of a concern.
Examples
Please note that these examples are distilled from test cases that automatically verify our functions still work correctly. This could explain some quirky ones.
# | code | expected result |
---|---|---|
1 | parse_url('https://user:pass@host/path?a=v#a') | {scheme: 'https', host: 'host', user: 'user', pass: 'pass', path: '/path', query: 'a=v', fragment: 'a'} |
2 | parse_url('https://en.wikipedia.org/wiki/%22@%22_%28album%29') | {scheme: 'https', host: 'en.wikipedia.org', path: '/wiki/%22@%22_%28album%29'} |
3 | parse_url('https://host.domain.tld/a@b.c/folder') | {scheme: 'https', host: 'host.domain.tld', path: '/a@b.c/folder'} |
4 | parse_url('https://gooduser:secretpassword@www.example.com/a@b.c/folder?foo=bar') | { scheme: 'https', host: 'www.example.com', path: '/a@b.c/folder', query: 'foo=bar', user: 'gooduser', pass: 'secretpassword' } |
Notes
original by https://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js blog post at https://blog.stevenlevithan.com/archives/parseuri demo at https://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js Does not replace invalid characters with ‘_’ as in PHP, nor does it return false with a seriously malformed URL. Besides function name, is essentially the same as parseUri as well as our allowing an extra slash after the scheme/protocol (to allow file:/// as in PHP)
Here’s what our current JavaScript equivalent to PHP's parse_url looks like.
module.exports = function parse_url(str, component) { |
A community effort
Not unlike Wikipedia, Locutus is an ongoing community effort. Our philosophy follows
The McDonald’s Theory.
This means that we assimilate first iterations with imperfections,
hoping for others to take issue with-and improve them.
This unorthodox approach has worked very well to foster fun and fruitful collaboration,
but please be reminded to use our creations at your own risk.
THE SOFTWARE IS PROVIDED "AS IS"
has never been more true than for Locutus.
Now go and: [ View on GitHub | Edit on GitHub | View Raw ]
Star