0

I'm using javascript to determine which directory an article is in, and self-generate all the file paths in the page. I've got it working, except that I still need to manually input the year the page was created as a variable when the article is moved from a 'recent' directory into the archive. I'm hoping to fully automate the process by using javascript to return the value of a specific directory in the file path.

For example, if the file path is: news/foo/2015/bar/article.html I need to extract the text '2015' and place it in a variable named 'year'.

Note the directory names won't be consistent, so I don't think searching the string for 'foo' or 'bar' is an option, rather the script needs to return the text between the second-last and third-last forward slash, or just the last 4 characters before the second-last forward slash. Thanks.

2 Answers 2

1

let p = "news/foo/2015/bar/article.htm";

let splitedPath = p.split('/');

// to get the right position of the year, may be the year position is dynamic;
let year = splitedPath.filter(ele => parseInt(ele)>0 && ele.length ==4);
console.log(year[0]);

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this, worked perfectly. I just had to add 'if (year == "")' to my existing code to cover the instances where the article is recent and yet to be filed under a specific year. Much appreciated answer.
1

Doesn't seem so bad, you can just use split:

let p = "news/foo/2015/bar/article.htm";

let year = p.split('/')[2];

You can also use parseInt if you want that as a proper number, if that matters.

1 Comment

Just throwing it out there, regex is another alternative if you really couldn't use split for some reason... but split definitely seems the better way to go.

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.