我有这个字符串,它是我想要重命名的文件的名称:
Planet.Earth.01.From.Pole.to.Pole.2006.1080p.HDDVD.x264.anoXmous_.mp4
我想从 2006 年开始删除这部分内容。我想尝试搜索不相关部分的索引并使用 JavaScript 字符串方法将其删除,但这对于其他可变长度文件不起作用。我怎样才能惯用地做到这一点?
最佳答案
假设文件名中仅出现一次 2006
,您可以尝试使用正则表达式替换:
var filename = "Planet.Earth.01.From.Pole.to.Pole.2006.1080p.HDDVD.x264.anoXmous_.mp4";
console.log(filename);
filename = filename.replace(/\.?2006.*(\.[^.]+)$/, "$1");
console.log(filename);
此处的策略是从 2006
开始进行匹配,同时捕获文件名的最终扩展名。然后,我们只替换该扩展名。我们还捕获了 2006 前面的一个前导 .
(如果存在),以确保替换中没有两个连续的 .
分隔符。
\.? match an optional leading dot (to avoid replacement with two consecutive dots)
2006 match "2006"
.* consume everything until
(\.[^.]+) capturing the file extension
$ end of the string
关于javascript - 如何匹配在字符串末尾终止的子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59421179/