我有一个像这样的网址字符串:
example.com/sfm?dir=uploads/sfm/root/folder1/subfolder1
是否有可能只使用javascript捕获=之后的部分?
所以抓住的部分应该是:uploads/sfm/root/folder1/subfolder1
答案 0 :(得分:2)
你可以试试这个(取自MDN):
var getQueryVarByName = function (name)
{
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
};
使用:
var param = getQueryVarByName('dir'); // uploads/sfm/root/folder1/subfolder1
答案 1 :(得分:1)
您可以使用split
在=
分割字符串并获取第二部分
var str = 'example.com/sfm?dir=uploads/sfm/root/folder1/subfolder1';
var part = str.split('=')[1];
console.log(part);
答案 2 :(得分:0)
您可以使用.split()
获取它:
var url = "example.com/sfm?dir=uploads/sfm/root/folder1/subfolder1";
var s = url.split('=')[1];
答案 3 :(得分:0)
您可以尝试此操作(使用.split()
):
function getFilePath(fullPath){
return fullPath.split("dir=")[1];
}
现在按以下方式调用它:
getFilePath("example.com/sfm?dir=uploads/sfm/root/folder1/subfolder1")
答案 4 :(得分:0)
您需要创建regexp。如果dir正则表达式之后有更多参数应该更复杂。
var url = 'example.com/sfm?dir=uploads/sfm/root/folder1/subfolder1';
var regexp = /dir=([\w\W]*)/;
var matched = url.match(regexp);
document.body.innerHTML = matched[1];

答案 5 :(得分:0)
问号?
后面的部分称为window.location.search
。您可能在此查询字符串中包含1个以上的参数。所以安全的解决方案应该是这样的:
//example.com/sfm?dir=uploads/sfm/root/folder1/subfolder1&un=test&time=1234
function getPath(){
var query=window.location.search //?dir=uploads/sfm/root/folder1/subfolder1&un=test&time=1234
.replace(/^\?/,'') //dir=uploads/sfm/root/folder1/subfolder1&un=test&time=1234
.split('&'); //[dir=uploads/sfm/root/folder1/subfolder1, un=test, time=1234]
for(var i = 0, n = query.length;i < n;i++){
var qs = query[i].split('=');
if(qs.length == 2 && qs[0] == 'dir')
return qs[1]; //if found
}//for
return null; // not found
}