John Manning
John Manning

Reputation: 39

Dynamic string cutting

Okay, so I have a filepath with a variable prefix...

C:\Users\susan ivey\Documents\VKS Projects\secc-electron\src\views\main.jade

... now this path will be different for whatever computer I'm working on...

is there a way to traverse the string up to say 'secc-electron\', and drop it and everything before it while preserving the rest of it? I'm familiar with converting strings to arrays to manipulate elements contained within delimiters, but this is a problem that I have yet to come up with an answer to... would there be some sort of regex solution instead? I'm not that great with regex so I wouldn't know where to begin...

Upvotes: 0

Views: 68

Answers (4)

Poul Bak
Poul Bak

Reputation: 10940

With Regex you can do:

var myPath = 'C:\Users\susan ivey\Documents\VKS Projects\secc-electron\src\views\main.jade'
var relativePath = myPath.replace(/.*(?=secc-electron)/, '');

The Regex is:

.*(?=secc-electron)

It matches any characters up to 'secc-electron'. When calling replace it will return the last part of the path.

Upvotes: 1

fnmps
fnmps

Reputation: 164

What you probably want is to do a split (with regex or not):

Here's an example:

var paragraph = 'C:\\Users\\susan ivey\\Documents\\VKS Projects\\secc-electron\\src\\views\\main.jade';
var splittedString = paragraph.split("secc-electron"); // returns an array of 2 element containing "C:\\Users\\susan ivey\\Documents\\VKS Projects\\" as the first element and "\\src\\views\\main.jade" as the 2nd element

console.log(splittedString[1]);

You can have a look at this https://www.w3schools.com/jsref/jsref_split.asp to learn more about this function.

Upvotes: 3

Maciej21592
Maciej21592

Reputation: 114

Alternatively you could use path.parse(path); https://nodejs.org/api/path.html#path_path_parse_path and retrieve the parts that you are interested in from the object that gets returned.

Upvotes: 0

Ethan Ryan
Ethan Ryan

Reputation: 500

You can split the string at a certain point, then return the second part of the resulting array:

var string = "C:\Users\susan ivey\Documents\VKS Projects\secc-electron\src\views\main.jade"

console.log('string is: ', string)

var newArray = string.split("secc-electron")

console.log('newArray is: ', newArray)

console.log('newArray[1] is: ', newArray[1])

Upvotes: 1

Related Questions