Home > database >  NodeJS - Split the string of two joined paths, to obtain a certain portion of the string
NodeJS - Split the string of two joined paths, to obtain a certain portion of the string

Time:08-18

Say we have a folder path like so...

/just/some/folder/location/

And a filepath like so...

this/way/for/the/file.txt

And we merge/join the two paths together to make a fullpath like so...

var folderPath = "/just/some/folder/location"
var filePath = "this/way/for/the/file.txt"

var joinedPath = path.join(folderPath, filePath);

How would I be able to cut the folderPath from the string, and keep only part of the filePath part so I'm left with an output like the example below?

way/for/the/file

CodePudding user response:

As you already have the individual variables, do don't have to first join and then remove the value of folderPath.

Using filePath you could capture from the first occurrence of / to before the last occurrence of a . using a pattern

const regex = /\/(\S )\./;
const str = `this/way/for/the/file.txt`;
const m = str.match(regex);

if (m) console.log(m[1]);

CodePudding user response:

Here is the solution code for your problem

var folderPath = "/just/some/folder/location"
var filePath = "this/way/for/the/file.txt"

//split with "/", splice for removing the first element and joining with a slash
filePath =  filePath.split("/").splice(1,filePath.length).join("/")
var joinedPath = path.join(folderPath, filePath);
  • Related