Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace second to last "/" character in URL with a '#'

I have this 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/

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/
like image 675
Laink Avatar asked Jun 22 '14 14:06

Laink


1 Answers

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/
like image 78
anubhava Avatar answered Sep 28 '22 01:09

anubhava