0

Hi I want to split a string in a specific way in javascript, like if the string is C:/users/Me/AppData/elastic/elastic 1.6. I know I can split it using the split() method and use pop() and shift() to get first and last splitted string but I want to split it like, except the last string. So the answer should be like “C:/users/Me/AppData/elastic"

I did it like this,

str.split(str.split("/").pop()).shift()

I got the out put like this,

C:/users/Me/AppData/

But I want it like this,

C:/users/Me/AppData
7
  • What exactly are you asking? What problems are you facing? Commented Oct 23, 2017 at 15:04
  • more importantly, what have you done so far to solve your issue? Commented Oct 23, 2017 at 15:05
  • I want split strings in JavaScript except the last word separated by the "/". Commented Oct 23, 2017 at 15:06
  • @rayancarlon - that is a task definition... We are asking where you are having problems with that task... Commented Oct 23, 2017 at 15:07
  • 1
    Possible duplicate of remove last directory in URL Commented Oct 23, 2017 at 15:11

2 Answers 2

2

It sounds like you're saying that you want the final item in the path to be dropped. To do that, you can use .lastIndexOf() to get the last / position, and then .slice() up to that point if it wasn't -1.

var str = "C:/users/Me/AppData/elastic/elastic 1.6";

var idx = str.lastIndexOf("/");
var res = str;

if (idx !== -1) {
  res = str.slice(0, idx);
}

console.log(res);

Or like this, which is similar to your attempt, but may be slower:

var str = "C:/users/Me/AppData/elastic/elastic 1.6";

var res = str.split("/");
res.pop();
res = res.join("/");

console.log(res);

Your original solution does work as long as the last item doesn't appear anywhere else in the URL. Otherwise you'll get only the part before the first split item.

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

Comments

0

If you want regex:

var str = "C:/users/Me/AppData/elastic/elastic 1.6"; 
str = str.replace(/\/[^\/]*$/, "");

The expression reads:

  1. Grab everything starting from / until the end of the string.
  2. There should be no / in between.
  3. Replace it with nothing

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.