Reputation: 109
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/
Upvotes: 5
Views: 334
Reputation: 174716
Below regex will capture /
which was just before to the last /
symbol.
.*(\/).*?\/$
Your javascript code would be,
var s ='http://localhost:8888/alain-pers/fr/oeuvres/architecture/';
var r = s.replace(/(.*)(\/)(.*?\/$)/, "$1#$3");
//=>http://localhost:8888/alain-pers/fr/oeuvres#architecture/
Upvotes: 4
Reputation: 59252
You can do this:
var str = "http://localhost:8888/alain-pers/fr/oeuvres/architecture/";
str = str.replace(/\/(\w+)(\/)?$/,"#$1$2");
Upvotes: 1
Reputation: 20014
How about something like this: /(\/)([\w-]+\/$)/
"http://localhost:8888/alain-pers/fr/oeuvres/architecture/"
.replace(/(\/)(\w+\/$)/,"#$2");
//outputs "http://localhost:8888/alain-pers/fr/oeuvres#architecture/"
Upvotes: 1
Reputation: 8225
Try this:
var output = input.replace(/\/([^\/]+\/[^\/]*)$/, "#$1" )
/*
input => "http://localhost:8888/alain-pers/fr/oeuvres/architecture/"
output => "http://localhost:8888/alain-pers/fr/oeuvres#architecture/"
*/
Upvotes: 3
Reputation: 785276
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/
Upvotes: 4