-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.

dda
  • 6,030
  • 2
  • 25
  • 34
Ivan Bora
  • 1
  • 1
  • 2

3 Answers3

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

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

PurkkaKoodari
  • 6,703
  • 6
  • 37
  • 58
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)
Davor Mlinaric
  • 1,989
  • 1
  • 19
  • 26
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.

Lee Meador
  • 12,829
  • 2
  • 36
  • 42