UniversalRouter params, query and hash

by Svetlana

HTML

<script src="https://npmcdn.com/[email protected]/universal-router.js"></script>

Babel + JSX

const location = new URL('http://example.com/user/45/posts/28/?sort=first#opened');

const route = {
  path: '/user/:userId/posts/:postId',
  action({ path, params: { userId, postId }, query: { sort }, hash }) {
    console.log(path);   // => '/user/45/posts/28/?sort=first#opened'
    console.log(userId); // => '45'
    console.log(postId); // => '28'
    console.log(sort);   // => 'first'
    console.log(hash);   // => '#opened'
    return /*...*/`
    path: ${path}<br/>
    userId: ${userId}<br/>
    sort: ${sort}<br/>
    hash: ${hash}`;
  }
}

// https://github.com/kriasoft/universal-router
UniversalRouter.resolve(route, {
  path: location.pathname,
  query: parseQuery(location.search),
  hash: location.hash,
}).then(result => {
  document.body.innerHTML = result
})

// https://github.com/sindresorhus/query-string
function parseQuery(qstr) {
  const query = {};
  const a = (qstr[0] === '?' ? qstr.substr(1) : qstr).split('&');
  for (let i = 0; i < a.length; i++) {
    const b = a[i].split('=');
    query[decodeURIComponent(b[0])] = decodeURIComponent(b[1] || '');
  }
  return query;
}