gpt4 book ai didi

Javascript:如何使用 RegExp 在 URL 中应用 "../"

转载 作者:行者123 更新时间:2023-11-29 18:04:56 25 4
gpt4 key购买 nike

什么是好的 RegExp 以通过删除它的相关父项来删除 URL 中的任何“../”?

例如:

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

到:

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

最佳答案

最好的方法是在循环中使用这个 RegEx:

[^\/]+\/\.\.\/

函数

然后你可以使用这个:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com