Reputation: 722
I have a string that takes the form of a path, for example:
Year 1 / English / Writing / How to write your name
I need to produce a string which is everything after the second forward slash. From the example above that means that my desired output would be:
Writing / How to write your name
I have seen a number of questions/answers regarding outputting the last part of a URL or getting a specific folder name in a file path but none of them have worked for me so far. I'll admit that my research hasn't been extensive due to time contraints.
My first thought is to do this in javascript with something like:
var input = "Year 1 / English / Writing / How to write your name";
var firstCut = input.substr(input.indexOf('/') + 1);
var secondCut = firstCut.substr(firstCut.indexOf('/') + 1);
I would prefer a more elegant solution, preferably using regex if possible!
Thanks
Upvotes: 1
Views: 2053
Reputation: 805
You could use ^.*?\/.*?\/
to remove the part you don't want.
Ex.
var string = 'Year 1 / English / Writing / How to write your name';
var result = string.replace(/^.*?\/.*?\//, '');
console.log(result);
if you want to capture the group use ^.*?\/.*?\/(.*)$
Upvotes: 0
Reputation: 3358
This regex will return an array in the form [entire string match, captured group]
. It starts at the beginning of the string and matches two groups of any number of characters that aren't /
followed by a /
, then captures the rest of the characters from there to the end of the string.
let test = "Year 1 / English / Writing / How to write your name"
let result = /^(?:[^\/]+\/){2}(.+)/.exec(test)[1]
console.log(result)
That said, the best answer is probably to use a split
and a join
:
let test = "Year 1 / English / Writing / How to write your name"
let result = test.split(/\s*\/\s*/).slice(2).join(" / ")
console.log(result)
Upvotes: 1
Reputation: 626738
You may use a replace
ing approach:
var s = "Year 1 / English / Writing / How to write your name";
var result = s.replace(/^(?:[^\/]*\/){2}\s*/, '');
console.log(result);
The pattern will match (and .replace
will eventually remove it):
^
- start of string(?:[^\/]*\/){2}
- two occurrences of
[^\/]*
- 0+ chars other than /
\/
- a /
char\s*
- 0+ whitespacesIn case there is no match, the result will be equal to the input string.
A matching approach might look like
var s = "Year 1 / English / Writing / How to write your name";
var result = (m = s.match(/^(?:[^\/]*\/){2}\s*([\s\S]+)/)) ? m[1] : "";
console.log(result);
The ([\s\S]+)
pattern will capture into Group 1 any one or more chars up to the string end after the initial text has matched the pattern described above.
In case there is no match, the result will be an empty string.
Upvotes: 3