Javascript:如何应用"/&引用;在带有RegExp的URL中

Javascript:如何应用"/&引用;在带有RegExp的URL中,javascript,jquery,regex,Javascript,Jquery,Regex,为了通过删除URL中的任何“。/”的相关父项来删除它,什么是好的RegExp 例如: http://www.example.com/main-directory/sub-directory/../index.html 致: 我认为您可以使用这样的正则表达式来删除父项: [^\/]*?\/\.\.\/ 或者在正则表达式下面使用 (.*?)[^\/]*?\/\.\.\/(.*) 并使用替换$1$2: 最好的方法是在循环中使用此正则表达式: [^\/]+\/\.\.\/ 作用 然后你可以使用这

为了通过删除URL中的任何“
。/
”的相关父项来删除它,什么是好的RegExp

例如:

http://www.example.com/main-directory/sub-directory/../index.html
致:


我认为您可以使用这样的正则表达式来删除父项:

[^\/]*?\/\.\.\/
或者在正则表达式下面使用

(.*?)[^\/]*?\/\.\.\/(.*)
并使用替换
$1$2


最好的方法是在循环中使用此正则表达式:

[^\/]+\/\.\.\/
作用 然后你可以使用这个:

function path(string, t) {
    return (t = string.replace(/[^\/]+\/\.\.\//,'')) !== string ? path(t) : t
}
如果您使用的是最新版本的JavaScriptES6,这会更好:

var path = (s,t) => (t = s.replace(/[^\/]+\/\.\.\//,'')) != s ? path(s) : s;
另类 如果您不喜欢函数:

while ( string != (string = string.replace(/[^\/]+\/\.\.\//,'')));

Thanx,但它不适用于multiple../,例如:对于
的多次使用。//
我建议您使用循环覆盖结果,而不是查找正则表达式;)。在严格模式下声明第一个
t
变量,或者只使用第二个参数作为帮助
var path=(s,t)=>(t=s.replace(/[^\/]+\/\.\/.\/,'')!=s?路径:s ;
while ( string != (string = string.replace(/[^\/]+\/\.\.\//,'')));