Play with URL API

by Julien Roche

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<section id="app">
  <form name="myForm" v-on:submit="submitForm">
    <label>
      <span>Type a valid url</span>
      <input type="url" name="url" v-model="currentURL" required="required" />
    </label>
  </form>

  <h2>URL itself</h2>
  <pre><code>{{ urlInstance }}</code></pre>
  
  <h2>URL query parameters</h2>
  <pre><code>{{ queryParameters }}</code></pre>
</section>

CSS

input {
  border: 2px solid black;
  margin-left: 2%;
  width: 75%;
}

input:valid {
  border-color: green;
}

input:invalid {
  border-color: red;
}

Babel + JSX

// https://developers.google.com/web/updates/2016/01/urlsearchparams?hl=en
// https://developer.mozilla.org/fr/docs/Web/API/URL
// https://developer.mozilla.org/fr/docs/Web/API/URLSearchParams
// https://www.npmjs.com/package/url-polyfill
let inputElement = document.querySelector('input');
let vueApp = new Vue({
  'el': '#app',
  'data': {
  	'currentURL': 'https://www.example.com/users?version=1.0',
    'urlInstance': null,
    'queryParameters': null
  },
  'methods': {
  	'analyzeURL': function () {
    	let url = new URL(this.currentURL);
    	let { hash, host, hostname, href, origin, password, pathname, port, protocol, search, username } = url;
        this.urlInstance = JSON.stringify({ hash, host, hostname, href, origin, password, pathname, port, protocol, search, username }, null, 3);
        this.queryParameters = JSON.stringify(Array.from(url.searchParams), null, 3);
    },
  	'submitForm': function (event) {
    	event.preventDefault();
      this.analyzeURL();
    }
  },
  'watch': {
  	'currentURL': function () {
    	this.analyzeURL();
    }
  },
  'mounted': function () {
  	this.analyzeURL();
  }
});