简体   繁体   中英

regex expression for replace method

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.

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"

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM