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

2
  • 3
    What have you tried so far? What problems have you encountered? Can you show the code you have so far? Commented Oct 12, 2010 at 8: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? Commented Oct 12, 2010 at 9:17

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

one bug in the cod please fix it "? urlString.substring(1) " to "? urlString.substring(1) : urlString);"
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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.