Home > Web Front-end > JS Tutorial > body text

How to parse url into json format using javascript

巴扎黑
Release: 2017-08-21 10:05:49
Original
2165 people have browsed it

This article mainly introduces two methods for javascript to parse url into json format. It has certain reference value. Interested friends can refer to it.

This article introduces how javascript parses url into json format. Two methods of json format are shared with everyone, as follows:

Method 1: The simplest method, use a tag to achieve


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)
Copy after login

Results obtained

Method 2: Through the url module of nodejs

You need to use Go to the url module provided by Node.js. It is very simple to use. Parse a string into a Url object through parse():


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

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' }
Copy after login

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template