0

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

aWebDeveloper
  • 36,687
  • 39
  • 170
  • 242
  • 3
    What have you tried so far? What problems have you encountered? Can you show the code you have so far? – Oded Oct 12 '10 at 08:11
  • You can check for the presence of http:// in the beginning of the string. Are there any exceptional cases apart from the above examples? – Salman A Oct 12 '10 at 09:17

3 Answers3

2

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

Community
  • 1
  • 1
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

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
  • 2,597
  • 4
  • 30
  • 43
0
<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

user473229
  • 11
  • 2