替换相对路径

发布于 2025-01-05 20:23:22 字数 279 浏览 3 评论 0原文

我需要去除相对 URL 的目录级别并用下划线替换斜杠。 其中一些相对 URL 包括上一级或两级(./ 或 ../../)。现在我正在使用:

$('area, a').click(function() { 
      cleanPath = $(this).attr('href').replace(/'..'/g, "").replace(/\//g, "_") );
});

但这不起作用。这里发布了类似的问题,但似乎没有解决我的具体问题。显然,我不是 RegEx 专家。

I need to strip the directory levels of a relative URL and replace slashes with underscores.
Some of those relative URLs include one or two levels up (./ or ../../). right now I'm using:

$('area, a').click(function() { 
      cleanPath = $(this).attr('href').replace(/'..'/g, "").replace(/\//g, "_") );
});

But that doesn't work. There are similar questions posted here but nothing that seems to address my specific issue. Obviously, I'm not a RegEx expert.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

笔芯 2025-01-12 20:23:22

您的正则表达式 /'..'/g 查找撇号后紧跟任何字符、紧随任何字符后跟另一个撇号的所有匹配项。这是因为 . 匹配除换行符之外的任何字符(除非启用多行模式)。

尝试以下任一操作:

/\.\./g

/[.]{2}/g

通过在前面添加反斜杠,您的正则表达式会将 . 视为文字 . (即句点)。

通过将 . 括在 [.] 中,正则表达式还将 . 视为文字 . ({2} 正好出现 2 次,连续出现)。

Your regex, /'..'/g looks for all matches of an apostrophe followed immediately by any character followed immediately by any character followed by another apostrophe. This is because . matches any character except newlines (unless multiline mode is enabled).

Try either:

/\.\./g

or

/[.]{2}/g

By prepending a backslash, your regex treats the . as a literal . (i.e., a period).

By enclosing . in [.], the regex also treats the . as a literal . ({2} is for exactly 2 occurences, back-to-back).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文