Skip to content Skip to sidebar Skip to footer

Remove The String Between The Last Two Slashes In A Url

I have the following url: http://website.com/testing/test2/ I want to remove the text between the last two slashes so this would produce: http://website.com/testing/

Solution 1:

Not sure if it is the best solution but it is simple and working:

var s = 'http://website.com/testing/test2/';
var a = s.split('/');

s = s.replace(a[a.length-2] + '/', '');
alert(s);`

Demo: http://jsfiddle.net/erkaner/xkhu92u0/1

Solution 2:

Here we get the last slash index in the string and subsctring from beginning to the slash index

text = text.substring(0, text.lastIndexOf("/")

that will result:

"http://website.com/testing/test2"// text

then did the same again get the last slach index and substring to this index + 1 and the +1 to include the slash again in the substring

text = text.substring(0, text.lastIndexOf("/")+1)

this will result:

"http://website.com/testing/"// text

do it in 1 line:

text = "http://website.com/testing/test2/"text = text.substring(0, text.substring(0, text.lastIndexOf("/")).lastIndexOf("/")+1)

Solution 3:

var url = 'http://website.com/testing/test2/', //URL to convert
    lastSlash = url.lastIndexOf('/'),          //Find the last '/'
    middleUrl = url.substring(0,lastSlash);    //Make a new string without the last '/'
lastSlash = middleUrl.lastIndexOf('/');        //Find the last '/' in the new string (the second last '/' in the old string)var newUrl = middleUrl.substring(0,lastSlash); //Make a new string that removes the '/' and everything after italert(newUrl);                                 //Alert the new URL, ready for use

This works.

Solution 4:

You can do something like this:

var missingLast = url.substring(0, url.substring(0, url.length -1).lastIndexOf('/'));

This will ignore the last slash first, then it will ignore the second to last slash.

NOTE: If you want to keep the last slash just add one to lastIndexOf like so:

var missingLast = url.substring(0, url.substring(0, url.length -1).lastIndexOf('/')+1);

Solution 5:

try something like this,

var url = 'http://website.com/testing/test2/';
var arr = url.split('/');
var lastWord = arr[arr.length-2];
var newUrl = url.substring(0, url.length-lastWord.length-1);
alert(newUrl);

demo in FIDDLE

Post a Comment for "Remove The String Between The Last Two Slashes In A Url"