开发者

Find out relative urls in javascript

开发者 https://www.devze.com 2023-01-19 10:20 出处:网络
I want to know if the url is relative or no using javascript. Basicallyi will be passed the url, if the url is relative append the current url i.eminus the file name. Can some one help me with this

I want to know if the url is relative or no using javascript. Basically i will be passed the url, if the url is relative append the current url i.e minus the file name. Can some one help me with this

eg:-

CURRENT URL = http://example.com/big/index.html

PASSED URL 1 = newindex.html

开发者_如何学Go OUTPUT = http://example.com/big/newindex.html

PASSED URL 2 = http://mysite.com/big/newindex.html

OUTPUT = http://mysite.com/big/newindex.html


So the simplest would be something like

var loc = location.href;
var dir = loc.substring(0,loc.lastIndexOf('/'));
function getHref(urlString) {
  if (urlString) return (urlString.toLowerCase().indexOf('http:')==0)?urlString:dir+'/'+((urlString.indexOf('/')==0)?urlString.substring(1):urlString);
}

I am using the location object, substring, indexOflink text, lastIndexOf and the ternary operator - nested


<script type="text/javascript">

    var loc = location.href;
    var baseurl = loc.substring(0,loc.lastIndexOf('/'));

    function getoutputurl(inputurl)
    {
        var returnurl = '';
        if (inputurl)
        {
            if(inputurl.toLowerCase().indexOf('http://')==0)
            {
                returnurl = inputurl;
            }
            else
            {
                returnurl =  baseurl+'/' ;
                if(inputurl.indexOf('/')==0)
                {
                    returnurl = returnurl + inputurl.substring(1);
                }
                else
                {
                    returnurl = returnurl + inputurl;
                }
            }
        }
        return returnurl;
    }

    alert(getoutputurl('http://google.com'));
    alert(getoutputurl('google.com'));
</script>

Try out this code it works


Use regular expresion to check if passed url have non relative component. If not create new output url based on part of current url ( cuted via regular exp also for example) and relative part.

0

精彩评论

暂无评论...
验证码 换一张
取 消