繁体   English   中英

正则表达式以从URL获取特定参数

[英]Regex to get a specific parameter from a URL

假设我们有这样的网址

HTTP://本地主机:8080 / dev.html组织=试验&位置= PR&LANG = FR

我想制作一个仅接受Organization = test的正则表达式,以便将其存储到var中。

所以如果我有http:// localhost:8080 / dev.html?organization = test ,我会得到organization = test。

http:// localhost:8080 / dev.html?lang = fr&organization = test ,我得到了organization = test。

无论URL的格式如何或参数的顺序如何,我都会得到

organization=<organization> 

谢谢

为什么要使用RegEx 或split 尝试这个:

function getOrganization(){
    return new URLSearchParams(location.search).get('organization')
}

(需要IE中URL API的polyfill)

您可以使用此函数, 即使该参数名确实包含RegExp认为特殊的任何字符,也可以假定该参数名不存在

 function getParam(url, name, defaultValue) { var a = document.createElement('a'); a.href = '?' + unescape(String(name)); var un = a.search.slice(1); var esc = un.replace(/[.?*+^$[\\]\\\\(){}|-]/g, '\\\\$&'); var re = new RegExp('^\\\\?&*(?:[^=]*=[^&]*&+)*?(' + esc + ')=([^&]*)'); a.href = url; var query = a.search; return re.test(query) ? query.match(re).slice(1).map(decodeURIComponent) : [un, defaultValue]; } var url = 'http://localhost:8080/dev.html?lang=fr&organization=test&crazy^ ()*key=cool'; console.log(getParam(url, 'organization')); console.log(getParam(url, 'lang')); console.log(getParam(url, 'crazy^ ()*key')); console.log(getParam(url, escape('crazy^ ()*key'))); console.log(getParam(url, encodeURIComponent('crazy^ ()*key'))); console.log(getParam(url, 'foo', 'bar')); 

RegExp转义方法是如何javascript中转义正则表达式的?

用法

getParam(url, name[, defaultValue])
  • url格式正确的URL
  • name -参数名称进行搜索
  • defaultValue (可选)-如果找不到,默认为什么值。 如果未指定,则defaultValue undefined
  • return - [ unescape(name), found ? stringValue : defaultValue ] [ unescape(name), found ? stringValue : defaultValue ]

为什么要使用正则表达式? 尝试这个。

function getOrganization(){
    var params = location.search.split('?')[1].split('&');
    for(var i = 0; i < params.length; i++){
        if(params[i].split('=')[0] == 'organization') return params[i].split('=')[1];
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM