截取的项目路径单个字符
通过 substring(0, 1) 截取了路径名的第一个字符,作为项目路径。请注意,这里的截取范围是从索引0开始,长度为1,因此实际上只截取了路径名的第一个字符。
代码语言:javascript复制// 获取项目路径
function getContextPath() {
debugger
var pathName = window.document.location.pathname;
//pathName: "/test/new_file.html"
var projectName = pathName.substring(0, 1);
//projectName: "/"
return projectName;
//项目路径
var contextPath = getContextPath();
console.log(contextPath)//打印:/
要获取完整的项目路径
想要获取完整的项目路径,可以尝试修改 substring() 的参数,例如使用 substring(0, pathName.indexOf("/", 1)) 来截取路径名中第一个斜杠之前的部分。
代码语言:javascript复制function getContextPath() {
var pathName = window.document.location.pathname;
var projectIndex = pathName.indexOf("/", 1);
var projectName = pathName.substring(0, projectIndex);
return projectName;
}
var contextPath = getContextPath();
console.log(contextPath); //打印:/test
test.html
代码语言:javascript复制<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
// // 获取项目路径
// function getContextPath() {
// debugger
// var pathName = window.document.location.pathname;
// //pathName: "/test/new_file.html"
// var projectName = pathName.substring(0, 1);
// //projectName: "/"
// return projectName;
// //项目路径
// var contextPath = getContextPath();
// console.log(contextPath)//打印:/
// //获取项目路径
// function getContextPath() {
// debugger
// var pathName = window.document.location.pathname;
// //pathName: "/test/new_file.html"
// var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') 1);
// //projectName: "/test"
// return projectName;
// }
// var contextPath = getContextPath();
// console.log(contextPath)//打印:/test
function getContextPath() {
var pathName = window.document.location.pathname;
var projectIndex = pathName.indexOf("/", 1);
var projectName = pathName.substring(0, projectIndex);
return projectName;
}
var contextPath = getContextPath();
console.log(contextPath); //打印:/test
</script>
</body>
</html>