作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何从给定的 URL 获取第一个斜杠后的值“如果有斜杠”?
如果 URL 是 domain.com
我想返回空字符串。
如果 URL 是 domain.com/index.html
我还想返回一个空字符串
如果 URL 是 domain.com/dev
或 domain.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/
我是一名优秀的程序员,十分优秀!