Python urljoin equivalent in AS3
Python has a function urljoin that takes two URLs and concatenates them intelligently. Is there a libr开发者_StackOverflow中文版ary that provides a similar function in AS3?
urljoin documentation: http://docs.python.org/library/urlparse.html
And python example:
>>> urljoin('http://www.cwi.nl/doc/Python.html', '../res/jer.png')
'http://www.cwi.nl/res/jer.png'
I want to know if there is an implementation of urljoin
function, not the whole urlparse
package
You can use for example the URI class from as3corelib
Usage:
import com.adobe.net.URI;
// create uri you want to be updated
var newURI:URI=new URI('../res/jer.png')
// update newURI with the full path
newURI.makeAbsoluteURI(new URI('http://www.cwi.nl/doc/Python.html'))
trace(uri.toString()) // will output http://www.cwi.nl/res/jer.png
// or make an utility function base on it:
function urljoin(url1:string, url2:String):String {
var uri:URI=new URI(url2)
uri.makeAbsoluteURI(url1)
return uri.toString()
}
Some raw code doing what you want, so you can skip all of the bloated libraries:
var urlJoin:Function = function(base:String, relative:String):String
{
// See if there is already a protocol on this
if (relative.indexOf("://") != -1)
return relative;
// See if this is protocol-relative
if (relative.indexOf("//") == 0)
{
var protocolIndex:int = base.indexOf("://");
return base.substr(0, protocolIndex+1) + relative;
}
// We need to split the domain and the path for the remaining options
var protocolIndexEnd:int = base.indexOf("://") + 3;
if (base.indexOf("/", protocolIndexEnd) == -1) // append slash if passed only http://bla.com
base += "/";
var endDomainIndex:int = base.indexOf("/", protocolIndexEnd);
var domain:String = base.substr(0, endDomainIndex);
var path:String = base.substr(endDomainIndex);
if (path.lastIndexOf("/") != path.length-1) // trim off any ending file name
path = path.substr(0, path.lastIndexOf("/")+1);
// See if this is site-absolute
if (relative.indexOf("/") == 0)
{
return domain + relative;
}
// See if this is document-relative with ../
while (relative.indexOf("../") == 0)
{
relative = relative.substr(3);
if (path.length > 1)
{
var secondToLastSlashIndex:int = path.substr(0, path.length-1).lastIndexOf("/");
path = path.substr(0, secondToLastSlashIndex+1);
}
}
// Finally, slap on whatever ending is left
return domain + path + relative;
};
精彩评论