Laink
Laink

Reputation: 109

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/

Upvotes: 5

Views: 334

Answers (5)

Avinash Raj
Avinash Raj

Reputation: 174716

Below regex will capture / which was just before to the last / symbol.

.*(\/).*?\/$

DEMO

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

Amit Joki
Amit Joki

Reputation: 59252

You can do this:

var str = "http://localhost:8888/alain-pers/fr/oeuvres/architecture/";
str = str.replace(/\/(\w+)(\/)?$/,"#$1$2");

Upvotes: 1

Dalorzo
Dalorzo

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

gp.
gp.

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

anubhava
anubhava

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

Related Questions