1

I am trying to get one back folder path from the url.But not working.I do not know how to get the path?

I expected url name like http://localhost/testing/ from http://localhost/testing/flower/

Example:

const path = require('path');

var url = http://localhost/testing/flower/

var reqPath = path.join(url, './');

console.log( reqPath );
2
  • 2
    ./ is current, not back. Commented Jul 29, 2019 at 13:22
  • this is an issue that doesn't need its own module. Just remove the last /if it exists then substring from start until last occurence of /. Add som handling of root path on that an you're golden Commented Jul 29, 2019 at 13:24

2 Answers 2

1

To go up a directory you use ../

const path = require('path');

var url = http://localhost/testing/flower/

var reqPath = path.join(url, '../');

console.log( reqPath );
Sign up to request clarification or add additional context in comments.

1 Comment

@charlietfl its is a valid call, i recommend looking up documentation for path nodejs.org/api/path.html#path_path_join_paths
1

I would recommend simple manual parsing of the string

function goUp(url){
  if (url.endsWith("/")) url = url.substring(0,url.length-1)
  const lastSlashPosition = url.lastIndexOf("/"); 

  return lastSlashPosition <=7 ? url: url.substring(0,lastSlashPosition);
}


console.log(goUp("http://localhost/"));
console.log(goUp("http://localhost/testing/flower"));
console.log(goUp("http://localhost/testing/flower/"));

1 Comment

Make sure to check for urls ending with a slash and check that the url isn't allready at the top

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.