用node.js搭建的服务器环境,其内置模块URL可以把浏览器传过来的URL进行解析,并根据解析结果做出相应的响应。1、引入node内置模块url,用url模块的parse方法来解析winUrl```javascriptvar url = require(‘url‘);var winUrl = url.parse(‘http://www.zhu.cn:80/ccc/index.html?name=zxt&age=26#33‘, true);console.log(winUrl); winUrl{ protocol: ‘http:‘, slashes: true, auth: null, host: ‘www.zhu.cn:80‘, port: ‘80‘, hostname: ‘www.zhu.cn‘, hash: ‘#33‘, search: ‘?name=zxt&age=26‘, query: { name: ‘zxt‘, age: ‘26‘ },当第二行的true不存在时query: ‘name=zxt&age=26‘, pathname: ‘/ccc/index.html‘, path: ‘/ccc/index.html?name=zxt&age=26‘, href: ‘http://www.zhu.cn:80/index.html?name=zxt&age=26#33‘ }``` 4、封装解析方法(解析URL中的问号参数值以及HASH值) ```javascript:runfunction queryURLParameter(url) { var obj = {}; var reg = /([^?=&#]+)=([^?=&#]+)/g; url.replace(reg, function () { obj[arguments[1]] = arguments[2]; }); reg = /#([^?=&#]+)/; if (reg.test(url)) { obj[‘HASH‘] = reg.exec(url)[1]; } return obj;}var str1="https://www.baidu.com/newspage/data/landingsuper?AAA=1111&BBB=222&CCC=333#1234";var abc1=queryURLParameter(str1);console.log("第1次输出:",abc1); function hashA(url){ var reg=/#([^#&=?]+)/; if(reg.test(url)){ return reg.exec(url)[1]; }}var str2="https://www.baidu.com/newspage/data/landingsuper?AAA=1111&BBB=222&CCC=333#1234"var abc2=hashA(str2);console.log("第2次输出:"+abc2); var ary=["零","一","二","三","四","五","六","七","八","九"];var str3="今年是2017年";var abc3=str3.replace(/\d/g,function () { return ary[arguments[0]]});console.log("第3次输出:"+abc3); /*正则匹配输出 我是[你的朋友]钱成*/var str4 = ‘我是<img src="haha.png" alt="你的朋友"/>钱成‘;var reg=/(.+)<(.+)t="(.+)"\/>(.+)/;var AAA=reg.exec(str4);var abc4=AAA[1]+"["+AAA[3]+"]"+AAA[4];console.log("第4次输出:"+abc4);```
原文地址:https://www.cnblogs.com/gushixianqiancheng/p/10967160.html
时间: 2024-11-08 21:15:41