1

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/

1
  • Use the regex pattern: /(http://.*?\/)[^\/]+\// Commented Apr 22, 2015 at 0:49

5 Answers 5

5

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

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

1 Comment

The JS fiddle is still alerting the whole URL.
1

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)

1 Comment

And...? Please add an explanation as to why this is the solution.
0

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 it
alert(newUrl);                                 //Alert the new URL, ready for use

This works.

1 Comment

It might not be the fastest, but it definitely works.
0

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);

Comments

0

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

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.