query-stringvsuri.js
The query-string library is a Node.js library that provides a simple way to parse and stringify query strings. It is useful for working with the query string portion of a URL, which is the part of the URL that follows 'the "?" character and contains key-value pairs.
URI.js is a lightweight JavaScript library for working with URLs and URIs in Node.js and the browser. It provides a simple and consistent interface for parsing, manipulating, and building URLs and URIs.
Example Use
import queryString from 'query-string';
console.log(location.search);
//=> '?foo=bar'
const parsed = queryString.parse(location.search);
console.log(parsed);
//=> {foo: 'bar'}
console.log(location.hash);
//=> '#token=bada55cafe'
const parsedHash = queryString.parse(location.hash);
console.log(parsedHash);
//=> {token: 'bada55cafe'}
parsed.foo = 'unicorn';
parsed.ilike = 'pizza';
const stringified = queryString.stringify(parsed);
//=> 'foo=unicorn&ilike=pizza'
location.search = stringified;
// note that `location.search` automatically prepends a question mark
console.log(location.search);
//=> '?foo=unicorn&ilike=pizza'
const URI = require('uri-js');
// parse url for values
const parsedUrl = URI.parse("https://www.example.com/search?q=query+string#fragment");
console.log(parsedUrl);
/* Output:
{
scheme: 'https',
authority: 'www.example.com',
path: '/search',
query: 'q=query+string',
fragment: 'fragment'
}
*/
// create url from values
const urlComponents = {
scheme: 'https',
authority: 'www.example.com',
path: '/search',
query: 'q=query+string',
fragment: 'fragment'
};
const url = URI.serialize(urlComponents);
console.log(url);
// Output: 'https://www.example.com/search?q=query+string#fragment'