2012-05-16 54 views
1

我的網址看起來像:正則表達式從URL中提取的散列參數在JavaScript

http://example.com/whatever#page?x=1&locale=hu&y=2 
http://example.com/whatever#page?x=1&locale=hu 
http://example.com/whatever#page?locale=hu 
http://example.com/whatever#page?locale= 
http://example.com/whatever#page?x=1 
http://example.com/whatever#page 
http://example.com/whatever 

我想獲得的區域設置參數或者爲空,如果它沒有設置。

我想是這樣的:

locale = location.hash.replace(/.*(?:[?&]locale=([^&]*))?.*/, "$2"); 

但我的問題是,我無法找到對所有情況(既當有ISN時,有語言環境=哈希和」工作權的RegExp t)

回答

15

下面是一段代碼將從哈希提取,並避免任何其他地方的網址:

function getLocaleFromHash(url) { 
    var match = url.match(/#.*[?&]locale=([^&]+)(&|$)/); 
    return(match ? match[1] : ""); 
} 

而且,你可以看到它在所有的測試案例在這裏工作:http://jsfiddle.net/jfriend00/p37Mx/


如果你希望能夠尋找在哈希任何PARM,你這樣做:

function getParmFromHash(url, parm) { 
    var re = new RegExp("#.*[?&]" + parm + "=([^&]+)(&|$)"); 
    var match = url.match(re); 
    return(match ? match[1] : ""); 
} 

看到它在這裏工作:http://jsfiddle.net/jfriend00/6kgUk/


將在網址提取所有參數更通用的功能是這樣的。對於散列位於查詢之後並且參數位於查詢字符串中的普通URL,它看起來像這樣。這是更多的代碼,因爲它更多。它獲取所有的參數到一個對象,你可以查找任何參數,通過它的關鍵,它的網址進行解碼他們太:

function getParmsFromURL(url) { 
    var parms = {}, pieces, parts, i; 
    var hash = url.lastIndexOf("#"); 
    if (hash !== -1) { 
     // remove hash value 
     url = url.slice(0, hash); 
    } 
    var question = url.lastIndexOf("?"); 
    if (question !== -1) { 
     url = url.slice(question + 1); 
     pieces = url.split("&"); 
     for (i = 0; i < pieces.length; i++) { 
      parts = pieces[i].split("="); 
      if (parts.length < 2) { 
       parts.push(""); 
      } 
      parms[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]); 
     } 
    } 
    return parms; 
} 

對於一個散列值和後處理參數的特殊版本?像在OP的問題的散列值(這不是典型情況),可以使用這樣的:

function getParmsFromURLHash(url) { 
    var parms = {}, pieces, parts, i; 
    var hash = url.lastIndexOf("#"); 
    if (hash !== -1) { 
     // isolate just the hash value 
     url = url.slice(hash + 1); 
    } 
    var question = url.indexOf("?"); 
    if (question !== -1) { 
     url = url.slice(question + 1); 
     pieces = url.split("&"); 
     for (i = 0; i < pieces.length; i++) { 
      parts = pieces[i].split("="); 
      if (parts.length < 2) { 
       parts.push(""); 
      } 
      parms[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]); 
     } 
    } 
    return parms; 
} 

工作演示:http://jsfiddle.net/jfriend00/v8cd5/

而且,然後如果你想在本地選項,倒是隻是這樣做:

var parms = getParmsFromURL(url); 
var locale = parms["locale"]; 
+0

我喜歡這個,因爲它很容易通過傳遞參數,我正在尋找函數:)可以重複使用:) – Gavriel

+0

@Gavriel - 我添加了一個更通用的函數,可以讓你傳遞的不僅是URL,而且參數你正在尋找它。 – jfriend00

+0

謝謝,我已經完成了它:)只是回來發佈它,但它是相同的你的第二個功能。 – Gavriel

2
locale = location.hash.match(/[?&]locale=([^&]*)?/); 
locale = (locale == null ? "" : locale[1] || ""); 

會做的伎倆。我不認爲.*是必要的,因爲你沒有指定字符串的開始或結束。 我在所有例子中測試了這個正則表達式,並且它們都正常工作:)

編輯:對不起,在某些情況下它是無效的。現在在所有情況下都是正確的。

0

如果你真的想這樣做,在一個正則表達式:

locale = location.hash.match(/([?&]locale=|^((?![?&]locale=).)+$)([^&]*)/)[3]; 

它可以對付你所有的例子,但我認爲它是非常低效的。