下面是我必须获取URL字符串的特定部分的工作代码:
const movieName = "frozen_2019";
const courseName = "olaf_is_enjoying_living_his_dream_1";
const source = "your majesty from https://example.com/english/courses/frozen_2019/olaf_is_enjoying_living_his_dream_1/voices/references/translate/do%20you%20hear%20that.mp3";
console.log(getSourceError(source)); // result
function getSourceError(source) {
const a = source.substring(source.indexOf(courseName) + courseName.length + 1);
const b = a.substring(a.lastIndexOf("/"));
return a.replace(b , "");
}
虽然它像预期的那样工作,但我认为应该有一个更干净的解决方案来做到这一点……
如您所见,我需要courseName
和URl末尾的file name
之间的字符串。
发布于 2020-09-29 08:31:41
我不完全确定您所说的cleaner解决方案是什么意思,但是这是一个使用regex的一行代码,假设您拥有与代码片段中相同的变量名。这就是你想要实现的吗?如果需要,可以修剪最后一个字符和第一个字符以删除斜杠。
const source = "your majesty from https://example.com/english/courses/frozen_2019/olaf_is_enjoying_living_his_dream_1/voices/references/translate/do%20you%20hear%20that.mp3";
const courseName = "olaf_is_enjoying_living_his_dream_1";
let extracted = source.match("(?<="+courseName+").*\/");
console.log(extracted);
发布于 2020-09-29 08:43:24
如您所见,我想要在courseName和
末尾的文件名之间的字符串。
在操作URL字符串时,最好使用以下命令将字符串拆分为数组:
let myURLArray = myURLString.split('/');
然后,在这种情况下,您可以使用:
indexOf()
splice()
join()
返回所需的URL部分。
工作示例:
const courseName = "olaf_is_enjoying_living_his_dream_1";
const source = "your majesty from https://example.com/english/courses/frozen_2019/olaf_is_enjoying_living_his_dream_1/voices/references/translate/do%20you%20hear%20that.mp3";
let sourceArray = source.split('/');
let courseNameIndex = sourceArray.indexOf(courseName);
let urlSectionArray = sourceArray.splice((courseNameIndex + 1), ((sourceArray.length - 1) - courseNameIndex - 1));
let urlSection = urlSectionArray.join('/');
console.log(urlSection);
发布于 2020-09-29 08:32:09
嗨,如果你的源码和它的结构是一致的,你可以拆分和加入你需要的部分。
source.split('/').splice(7,3).join('/')
https://stackoverflow.com/questions/64115618
复制相似问题