替换倒数第二个“/"URL 中带有“#"的字符 [英] Replace second to last "/" character in URL with a '#'

查看:58
本文介绍了替换倒数第二个“/"URL 中带有“#"的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个网址:

http://localhost:8888/alain-pers/fr/oeuvres/architecture/

我想用 # 替换倒数第二个 /(我需要最后一个 /)并得到以下输出:

I would like to replace the second to last / with # (I need the last /) and get the following output:

http://localhost:8888/alain-pers/fr/oeuvres#architecture/

我用 indexOf()lastIndexOf()substr() 尝试了很多方法,但我不能得到我想要的结果.我也无法让任何正则表达式解决方案正常工作.

I've tried a lot of things with indexOf(), lastIndexOf() and substr(), but I can't get the result I want. I couldn't get any regex solution to work properly, either.

请注意,有时链接看起来像这样,也带有 -:

Note that sometimes the link looks like this, with a -, too:

http://localhost:8888/alain-pers/fr/oeuvres/art-contemporain/

推荐答案

您可以使用这个基于前瞻的正则表达式:

You can use this lookahead based regex:

var s ='http://localhost:8888/alain-pers/fr/oeuvres/architecture/';
var r = s.replace(/\/(?=[^/]*\/[^/]*$)/, '#');
//=> http://localhost:8888/alain-pers/fr/oeuvres#architecture/

这篇关于替换倒数第二个“/"URL 中带有“#"的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆