gpt4 book ai didi

javascript - 如何使用javascript从URL中获取斜杠后的值?

转载 作者:行者123 更新时间:2023-11-29 21:46:26 26 4
gpt4 key购买 nike

如何从给定的 URL 获取第一个斜杠后的值“如果有斜杠”?

如果 URL 是 domain.com 我想返回空字符串。

如果 URL 是 domain.com/index.html 我还想返回一个空字符串

如果 URL 是 domain.com/devdomain.com/dev/new/blah.html 我想返回 'dev'

注意:我不知道第一个斜线后的值是什么

这是我做的

var icwsSiteBaseURL = document.location.pathname.split("/").slice(1, 2).toString();

我的代码适用于第一个和第三个示例,但不会为第二个示例返回空字符串。它将返回 index.html

最佳答案

您只需检查要忽略的值的结果。这是一个例子:

var domains = [
'domain.com',
'domain.com/index.html',
'domain.com/dev',
'domain.com/dev/new/blah.html'
];

var results = domains.map(function (domain) {
// This would be document.location.path in your example
var path = domain.split('/')[1] || '';

// Check path if it matches the value you want to ignore
return { domain: domain, result: path === 'index.html' ? '' : path };
});

document.write('<pre>' + JSON.stringify(results, null, 4) + '</pre>');

因此,对于您的示例代码:

var icwsSiteBaseURL = document.location.pathname.split("/").slice(1, 2).toString();
if (icwsSiteBaseURL === 'index.html') { icwsSiteBaseURL = ''; }

关于javascript - 如何使用javascript从URL中获取斜杠后的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31035133/

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