Home >Web Front-end >JS Tutorial >How to parse url into json format using javascript
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)
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'));
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 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!