URI.jsでURLをパースする

URLをパースするの、面倒ですよね。URI.jsが便利なので使いましょう:

<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/URI.js/1.19.0/URI.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
let uri = new URI();
let functions = ['hostname', 'directory', 'filename', 'segment', 'path'];

$(document).ready(function(){

  for(let i=0; i<functions.length; i++){
    console.log(functions[i] + ": " +  uri[functions[i]]() );
  }

});
</script>
</head>
<body>
</body>
</html>

上記のコードをhttp://thebaker.test/hoge/foo/test.htmlとした場合、コンソールには以下が表示されます:

hostname: thebaker.test
directory: /home/foo
filename: test.html
segment: hoge, foo, test.html
path: /hoge/foo/test.html

またクエリパラメータは次のようにとれます:

var uri = new URI();
var query_strings = uri.query(true); // trueを指定するとjson形式で返却してくれる
var page_no = query_strings['page_no'];