2017-06-08 38 views
0

我是新來的JavaScript,我需要幫助解決的問題。獲取URL的特定部分使用JavaScript

我有以下網址:

http://localhost/solo04/index.php?route=checkout/checkout#shipping-method

我想剛纔得到的URL(路徑=檢出/檢出)的那部分如何做到這一點?

+0

https://stackoverflow.com/questions/39619951/regular-expression-for-鏈接/ 39620022#39620022 –

回答

0

var str1 = "http: //localhost/solo04/index.php? Route = checkout/checkout # shipping-method"; 
 
    var n = str1.lastIndexOf("?")+1; 
 
    alert(str1.substr(n));

1

您可以創建一個超鏈接元素來做到這一點,只需創建它像平時那樣,但不追加到DOM:

var parser = document.createElement('a'); 
parser.href = "http://example.com:3000/pathname/?search=test#hash"; 

parser.protocol; // => "http:" 
parser.hostname; // => "example.com" 
parser.port;  // => "3000" 
parser.pathname; // => "/pathname/" 
parser.search; // => "?search=test" 
parser.hash;  // => "#hash" 
parser.host;  // => "example.com:3000" 

如果再需要查詢字符串,你可以使用類似的東西來解析它:

function getQueryVariable(variable) { 
    var query = window.location.search.substring(1); 
    var vars = query.split('&'); 
    for (var i = 0; i < vars.length; i++) { 
     var pair = vars[i].split('='); 
     if (decodeURIComponent(pair[0]) == variable) { 
      return decodeURIComponent(pair[1]); 
     } 
    } 
    console.log('Query variable %s not found', variable); 
} 

爲了得到一個特定的變量。

貸給jlong​​ &塔裏克爲優秀的想法。

1

最簡單的方法是使用regexsplit

url = "http://localhost/solo04/index.php?Route=checkout/checkout#shipping-method"; 

lastPart = url.split('?')[1]; // grabs the part on the right of the ? 

console.log(lastPart); 

更多的變種列How to get the value from the GET parameters?

2

我想扔了這一點,也因爲我不認爲它已經提到這裏。 您可以使用新的API URL也避免我看到了一些在這裏的答案任何regex或任何字符串操作。

但是,這是相對比較新的舊的瀏覽器支持這個功能可能會受到限制。

如:

var myURL = new URL('http://localhost/solo04/index.php?q=somequery'); 
console.log(myURL); 

這會給你一個對象,它應該有pathhostnamesearch