Javascript 使用replace()从存储在数组中的每个链接获取id?
链接列表取自输入,而输入中的每个链接用空格分隔,以便以后可以在代码中拆分。我尝试使用以下代码,目标是只生成数组中所有链接的id部分。但它只会导致第一个链接的id,其余链接保持不变 以下是两个示例链接:Javascript 使用replace()从存储在数组中的每个链接获取id?,javascript,jquery,Javascript,Jquery,链接列表取自输入,而输入中的每个链接用空格分隔,以便以后可以在代码中拆分。我尝试使用以下代码,目标是只生成数组中所有链接的id部分。但它只会导致第一个链接的id,其余链接保持不变 以下是两个示例链接: https://drive.google.com/file/d/1jTZ37iVWdb6MEs1HQzFtkKaOmEVNoG9n/view?usp=sharing https://drive.google.com/file/d/1QlwvBmXzO56Prq4WLERS4tpD2Kcp2yOr
https://drive.google.com/file/d/1jTZ37iVWdb6MEs1HQzFtkKaOmEVNoG9n/view?usp=sharing
https://drive.google.com/file/d/1QlwvBmXzO56Prq4WLERS4tpD2Kcp2yOr/view?usp=sharing
以下是jquery:
$("#checklist").on("click", function () {
var value = $("#uploadlist").val();
var arr= value.split(" ")
$.each(arr, function(key, list){
if (list.startsWith("https://drive.google.com/file/d/") &
list.endsWith("/view?usp=sharing")) {
var id1 = list.replace("https://drive.google.com/file/d/", "");
var id= id1.replace("/view?usp=sharing", "");
console.log(id)
})
我还尝试使用:
var id= list.replace("https://drive.google.com/file/d/", "").replace("/view?
usp=sharing","");
console.log(id);
\nhttp
var链接=`https://drive.google.com/file/d/1jTZ37iVWdb6MEs1HQzFtkKaOmEVNoG9n/view?usp=sharing
https://drive.google.com/file/d/1QlwvBmXzO56Prq4WLERS4tpD2Kcp2yOr/view?usp=sharing
`;
链接=链接
.split(/\nhttp/)
.map((链接)=>{
返回链接。替换(/(.*)文件\/d\/,“”)。替换(/\/视图(.*?+\n/,“”);
});
控制台日志(链接)代码>发现您的错误:
你写道:
list.endsWith("/viewusp=sharing"))
而不是
list.endsWith("/view?usp=sharing"))
最好将URL的开头和结尾放在一个变量中,不要重复它们
$("#checklist").on("click", function () {
const start = "https://drive.google.com/file/d/"
const end = "view?usp=sharing"
var value = $("#uploadlist").val();
var arr= value.split(" ")
$.each(arr, function(key, list){
if (list.startsWith(start) & list.endsWith(end)) {
const id = list.replace(start,"").replace(end,"");
console.log(id);
}
});
//The rest of your code here
});
为什么要按空格字符(value.split(“”
)拆分上载列表?如果要匹配URL的各个部分,最好按斜杠(value.split(“/”)拆分,然后从所需的URL部分检索ID。我按空格字符拆分它,以便If语句可以检查数组的每个元素是否以开头https://drive.google.com/file/d/“
并包括”/viewusp=共享”
如果这是一个输入错误,为什么第一个URL可以使用,而其他URL不能使用?噢,天哪,那只是一个输入错误。这在我试图运行的实际代码中不会发生。谢谢:)我会修好的。该死的你是一个javascript上帝:-哦,谢谢!