什么是好的正则表达式,可以通过删除其相关父级来删除 URL 中的任何“../
”?
例如:
http://www.example.com/main-directory/sub-directory/../index.html
至:
http://www.example.com/main-directory/index.html
最佳答案
最好的方法是在循环中使用此正则表达式:
[^\/]+\/\.\.\/
函数
然后你可以使用这个:
function path(string, t) {
return (t = string.replace(/[^\/]+\/\.\.\//,'')) !== string ? path(t) : t
}
如果您使用最新版本的 JavaScript ES6,效果会更好:
var path = (s,t) => (t = s.replace(/[^\/]+\/\.\.\//,'')) != s ? path(s) : s;
替代方案
如果您不喜欢函数:
while ( string != (string = string.replace(/[^\/]+\/\.\.\//,'')));
关于Javascript:如何使用 RegExp 在 URL 中应用 "../",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32031794/