gpt4 book ai didi

javascript - 通过replace()方法将年份放在括号中

转载 作者:行者123 更新时间:2023-11-30 11:30:33 24 4
gpt4 key购买 nike

我有一个这种类型的输入,例如:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com