我想知道如何解析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”
我应该怎么办呢?
谢谢!
我想知道如何解析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”
我应该怎么办呢?
谢谢!
试试这个:
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
另一种方法是使用正则表达式是这样的:
.*?mydomain\.com[^\/]*\/[^\/]+\/[^\/]+\/([^?]*)
(Breakdown of the components.)
这看起来对于它跳过模式域之前,无论发生什么事名称(如果协议被指定,则无关紧要),跳过域名+ TLD,跳过任何端口号,并跳过前两个子路径元素。然后选择后面的任何内容,但跳过任何查询字符串。
在代码中,你可以使用它像这样:
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
编辑:固定在正则表达式字符串
简单的办法,
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'
嗨 - 你可以添加一些上下文你正在试图解决这个问题?即这是来自浏览器的URL还是来自表单的输入?你是否总是需要URL路径中的最后两个参数? – alph486 2014-10-31 16:28:57
你好,它会来自浏览器。 我总是需要一些在“某事”之后出现的东西(注意,某些东西是动态的) – user2894688 2014-10-31 16:33:51