簡體   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