5

Using window.location.pathname I get "/Mobile/Evol/12-20-2011".

Using Javascript, how could I drop off everything after "Evol/" so that I get "/Mobile/Evol/"?

2
  • 2
    BTW, what's your real goal? Commented Dec 21, 2012 at 16:55
  • @MaratTanalin I second that. From what you wrote, it isn't clear what, in general, you're actually trying to accomplish. Commented Dec 21, 2012 at 16:56

5 Answers 5

6

You can use a combination of the substring() and lastIndexOf() functions to easily cut off everything after the last /:

uri    = "/Mobile/Evol/12-20-2011";
newUri = uri.substring(0, uri.lastIndexOf('/'));

as @josh points out if there are more directories after "/Evol", this fails. You can fix this by searching for the string 'Evol/' then adding its length back to the substring end:

dir = "Evol/";
newUri = uri.substring(0, uri.lastIndexOf(dir) + dir.length);

Chrome console gives me this output:

> uri    = "/Mobile/Evol/12-20-2011";
"/Mobile/Evol/12-20-2011"

> dir = "Evol/";
  newUri = uri.substring(0, uri.lastIndexOf(dir) + dir.length);
"/Mobile/Evol/"
Sign up to request clarification or add additional context in comments.

2 Comments

This assumes there's only one directory after Evol, which may not be correct.
@josh3736 that is correct, I was only following the example that was posted. I edited to take account for your comment.
2

Just use "split" function in JavaScript string,

var url = '/Mobile/Evol/12-20-2011';
var tokens = url.split('/');
var reqURL = token[0] + '/'+ token[1] ;

Of course the URL format must be the same some_string/some_string/some_string

Comments

0
var str = window.location.pathname;
const sub = "Evol/";

var locEvol = str.indexOf(sub);
var endIdx = locEvol + sub.length;
var beginStr = str.substring(0, endIdx);
// beginStr contains the desired substring

Comments

0

Assuming you want to cut off any query and fragment completely:

url.replace(/\/Evol\/[^?#]*(?:[?#].*)?$/, '/Evol')

To break this regex down:

  1. \/Evol\/ matches the literal text "/Evol/". The \'s are necessary since //Evol/... would be a line comment, and a / elsewhere in a regex ends the regex.
  2. [^?#] matches anything except a query or fragment delimiter
  3. (?:...)? just makes something optional
  4. [?#].* matches a query or fragment start followed by any number of non-whitespace chars
  5. $ forces the match to reach the end of the input.

Comments

0

One Liner:

match.url.split("/").slice(0,-1).join("/")

let array1 = "/first/second/third/fourth";
let array2="posts/stories/1234";

console.log("Result=",array1.split("/").slice(0,-1).join("/"));
console.log("Result=",array2.split("/").slice(0,-1).join("/"));

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.