tags:

views:

49

answers:

3

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
OUTPUT = http://example.com/big/newindex.html

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

A: 

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.

zgorawski
+1  A: 

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

mplungjan
can u explain your code a bit
Web Developer
Please see my amended answer
mplungjan
one bug in the cod please fix it "? urlString.substring(1) " to "? urlString.substring(1) : urlString);"
Web Developer
Done - thanks!!!
mplungjan
Obviously not enough?
mplungjan
+1 ^ for your effort
Web Developer
Thanks for the vote
mplungjan
+1  A: 
<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