2014-10-31 90 views
0

我想知道如何解析URL。解析URL(ActionScript 3.0)

協議://mydomain.com/something/morethings/this_is_what_i_want/even_if_it_has_slashes

我需要得到 「this_is_what_i_want/even_if_it_has_slashes」

我應該怎麼辦呢?

謝謝!

+0

嗨 - 你可以添加一些上下文你正在試圖解決這個問題?即這是來自瀏覽器的URL還是來自表單的輸入?你是否總是需要URL路徑中的最後兩個參數? – alph486 2014-10-31 16:28:57

+0

你好,它會來自瀏覽器。 我總是需要一些在「某事」之後出現的東西(注意,某些東西是動態的) – user2894688 2014-10-31 16:33:51

回答

0

試試這個:

var u:String = 'protocol://mydomain.com/something/morethings/this_is_what_i_want/even_if_it_has_slashes', 
    a:Array = u.split('/'), 
    s:String = '' 

for(var i=0; i<a.length; i++){ 
    if(i > 3){ 
     s += '/'+a[i] 
    } 
} 

trace(s) // gives : /morethings/this_is_what_i_want/even_if_it_has_slashes 
0

另一種方法是使用正則表達式是這樣的:

.*?mydomain\.com[^\/]*\/[^\/]+\/[^\/]+\/([^?]*) 

Breakdown of the components.

這看起來對於它跳過模式域之前,無論發生什麼事名稱(如果協議被指定,則無關緊要),跳過域名+ TLD,跳過任何端口號,並跳過前兩個子路徑元素。然後選擇後面的任何內容,但跳過任何查詢字符串。

例子:http://regexr.com/39r69

在代碼中,你可以使用它像這樣:

var url:String = "protocol://mydomain.com/something/morethings/this_is_what_i_want/even_if_it_has_slashes"; 
var urlExp:RegExp = /.*?mydomain\.com[^\/]*\/[^\/]+\/[^\/]+\/([^?]*)/g; 
var urlPart:Array = urlExp.exec(url); 
if (urlPart.length > 1) { 
    trace(urlPart[1]); 
    // Prints "this_is_what_i_want/even_if_it_has_slashes" 
} else { 
    // No matching part of the url found 
} 

正如你可以在上面的regexr鏈接上看到,這抓住了部分 「this_is_what_i_want/even_if_it_has_slashes」爲所有這些變化的url:

protocol://mydomain.com/something/morethings/this_is_what_i_want/even_if_it_has_slashes 
protocol://mydomain.com:8080/something/morethings/this_is_what_i_want/even_if_it_has_slashes 
protocol://mydomain.com/something/morethings/this_is_what_i_want/even_if_it_has_slashes.html 
protocol://mydomain.com/something/morethings/this_is_what_i_want/even_if_it_has_slashes.html?hello=world 
mydomain.com/something/morethings/this_is_what_i_want/even_if_it_has_slashes 
protocol://subdomain.mydomain.com:8080/something/morethings/this_is_what_i_want/even_if_it_has_slashes 

編輯:固定在正則表達式字符串

0

簡單的辦法,

var file:String = 'protocol://mydomain.com/something/morethings/this_is_what_i_want/even_if_it_has_slashes'; 
    var splitted:Array = file.split('/'); 
    var str1:String = splitted.splice(3).join('/'); //returns 'something/morethings/this_is_what_i_want/even_if_it_has_slashes' 
    var str1:String = splitted.splice(5).join('/'); //returns 'this_is_what_i_want/even_if_it_has_slashes'