-5

I have a string:

http://a.long.url/can/be/here/jquery.min.js?207

I need to extract the base URL http://a.long.url/can/be/here/ using Javascript. So it should be split on the first / from the right.

2

3 Answers 3

1

try with this

var url = 'http://a.long.url/can/be/here/jquery.min.js?207';
var path = url.split( '/' );
var stripped = "";
for ( i = 0; i < path.length-1; i++ ) {
    if(i>0) stripped += "/";
    stripped += path[i];
}
alert(stripped)
Sign up to request clarification or add additional context in comments.

Comments

1
url.substring(0, url.lastIndexOf("/") + 1)

Remove the + 1 if you don't want the / in the end.

1 Comment

Note that this returns an empty string if the url does not contain a /, e.g. if it's simply www.mydomain.com.
0
var url = "http://my.com:8080/path/bob.js?query"

var col1 = url.indexOf("?");
if (col1 > 0) {
    var col = url.substring(0,col1).lastIndexOf("/");
} else {
    col = url.lastIndexOf("/");
}

var extracted = url.substring(0, col);

Without checking for errors. (For example, what if the url string has no slashes at all. It's not a valid URL but it could be passed to this code.) Note also that it doesn't work if the question mark is the first character.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.