我有一个这种类型的输入,例如:
Star Wars 1977
输出应该是:
Star Wars (1977)
如何使用 replace() 方法获取它?
最佳答案
您可以使用正则表达式匹配年份,然后替换它:
var str = "Star Wars 1977";
str = str.replace(/(\d{4})/, '($1)'); // $1 is the first match, which is the year
console.log(str);
如果你处理的是电影,有些电影的标题中有年份,因此,为了与标题中的年份不匹配,你可以只在字符串末尾捕获年份:
var str = "2001: A Space Odyssey 1968";
str = str.replace(/(\d{4})$/, '($1)'); // $1 is the first match, which is the year
console.log(str);
关于javascript - 通过replace()方法将年份放在括号中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46390095/