Home  >  Article  >  Web Front-end  >  Two methods for javascript to parse url into json format

Two methods for javascript to parse url into json format

韦小宝
韦小宝Original
2018-01-19 10:35:562114browse

This article mainly introduces javascript two methods of parsing url into json format. It has certain reference and value for learning JavaScript. Friends who are interested in JavaScript can refer to this article. Article

This article introduces two methods for javascript to parse URLs into json format. I would like to share them with you. The details are as follows:

Method 1: The simplest method is to use the a tag to The result obtained by implementing

function parseUrl(url){
  var a=document.createElement('a');
  a.href=url;
  return {
   protocol:a.protocol.replace(':',''),
   hostname:a.hostname,
   port:a.port,
   path:a.pathname,
   query:(()=>{
    var query=a.search.substr(1);
    var queryArr=query.split('&');
    var queryObj={};
    queryArr.forEach((item,index)=>{
      var item=item.split('=');
      var key=item[0];
      queryObj[key]=item[1];
    })
    return queryObj;
   })(),
    params:(()=>{
    var params=a.hash.substr(1);
    var paramsArr=params.split('#');
    return paramsArr;
    
   })(),

  }
}
var urlObj = parseUrl('http://www.baidu.com:90/search?name=liyajie&age=12#abc#bbb')
console.log(urlObj)

:

Method 2: Through the url module of nodejs

Parsing URLs requires the use of the url module provided by Node.js. It is very simple to use. It uses parse() to parse a string into a Url object:

  'use strict';
   var url = require('url');
   console.log(url.parse('http://user:pass@host.com:8080/path/to/file?query=string#hash'));

Returned results:

Url {
 protocol: 'http:',
 slashes: true,
 auth: 'user:pass',
 host: 'host.com:8080',
 port: '8080',
 hostname: 'host.com',
 hash: '#hash',
 search: '?query=string',
 query: 'query=string',
 pathname: '/path/to/file',
 path: '/path/to/file?query=string',
 href: 'http://user:pass@host.com:8080/path/to/file?query=string#hash' }

The above is the entire content of this article. I hope it will be helpful to everyone's learning, and I also hope that everyone will support the PHP Chinese website.

Related recommendations:

Javascript Summary of several methods of generating random numbers

JavaScript implementation code for shielding the Backspace key

JavaScript implementation of lottery system example sharing

The above is the detailed content of Two methods for javascript to parse url into json format. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn