2

I have a string like

/abc/def/hij/lmn.o // just a raw string for example dont know what would be the content

I want only /abc/def/hij part of string how do I do that.

I tried using .split() but did not get any solution.

0

4 Answers 4

3
  1. If you want to remove the particular string /lmn.o, you can use replace function, like this

    console.log(data.replace("/lmn.o", ""));
    # /abc/def/hij
    
  2. If you want to remove the last part after the /, you can do this

    console.log("/" + data.split("/").slice(1, -1).join("/"));
    # /abc/def/hij
    
Sign up to request clarification or add additional context in comments.

2 Comments

@Pilot I believe the second method in my answer already answers your question.
thanks ..the 2nd one solves my problem..but I think Its kind of heavy op than REGEX so accepting other as ans
2

you can do

var str = "/abc/def/hij/lmn.o";
var dirname = str.replace(/\/[^/]+$/, "");

Alternatively:

var dirname = str.split("/").slice(0, -1).join("/");

See the benchmarks

dirname benchmark

4 Comments

Great..this is what I was probably looking for
x.substring(0,x.lastIndexOf("/")); My answer seems to be simple. Yet this is the best answer. Keeps me thinking if I got it wrong :D
@faiz, your answer is completely fine. In fact, in the benchmark I setup, yours performs the best.
Thanks for genuine comment
1

Using javascript

var x = '/abc/def/hij/lmn.o';
var y = x.substring(0,x.lastIndexOf("/"));
console.log(y);

Comments

0
var s= "/abc/def/hij/lmn.o"
var arr= s.split("/");

after this, use

arr.pop();

to remove the last content of the array which would be lmn.o, after which you can use

var new_s= arr.join("/");

to get /abc/def/hij

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.