1

I am trying to extract the year in ( ) for a given title

Example:

"This is 40 (2012)"

returns: "This is 40"

title = mTitle.replace(/[^a-zA-Z:\s]/g, '');

This works except for titles that also have a number before the parenthesis. I'm also trying to get the year.

year = mTitle.replace(/\D+/g, '');

I having a trouble wrapping my mind around it.

0

2 Answers 2

4

To remove trailing year(digits) surrounded by parentheses:

> "This is 40 (2012)".replace(/\(\d+\)$/, '')
"This is 40 "

To also remove spaces before year part:

> "This is 40 (2012)".replace(/\s*\(\d+\)$/, '')
"This is 40"
Sign up to request clarification or add additional context in comments.

4 Comments

That works great. What about just the year inside the parentheses?
@MickB, I don't understand what do you mean. Do you want get 2012 from This is 40 (2012)?
@MickB, Try "This is 40 (2012)".match(/\((\d+)\)$/)[1]. This give you "2004"
Yes, I did the same thing with the year and I am getting all the numbers instead of just the year in the paranethses
0

You could use one of these options :

var year = 'This is 40 (2012)'.slice(-5, -1);
var year = 'This is 40 (2012)'.match(/\d+(?=.$)/)[0];
// regex : one or more digits followed by any char + end of string
var year = 'This is 40 (2012)'.replace(/^.*?(\d+).$/, '$1');
// regex : zero or more chars + one or more digits ($1) + any char

Doc : slice, match, replace, regular expressions.

Comments

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.