Staffan Estberg
Staffan Estberg

Reputation: 7025

Replace last forward slash in string with other character

I'm trying to replace the last forward slash in a series of url strings, to exchange that forward slash for a number sign, like so -

http://example.com/about/our-company

to

http://example.com/about#our-company

Using JS with jQuery I've tried applying the replace function on each string but not sure as how to target just the last forward slash.

$('.submenu a').each(function() {
    var url = $(this).attr('href');
    url = url.replace(/\//g, '#');
    console.log(url);
    // replaces all
});

Upvotes: 6

Views: 5427

Answers (4)

Dhanu Gurung
Dhanu Gurung

Reputation: 8840

You can try splitting Url based on /:

url = 'http://example.com/about/our-company';
tokens = url.split('/');
expected_url = tokens.slice(0, tokens.length-1).join('/') + '#' + tokens[tokens.length-1];

console.log(expected_url);
# Prints 'http://example.com/about#our-company'

Upvotes: 2

kcak11
kcak11

Reputation: 842

A simple solution:

var str="http://example.com/about/our-company";
var tmp=str.split("").reverse().join("");
tmp=tmp.replace("/","#");
str=tmp.split("").reverse().join("");

//output:

str = http://example.com/about#our-company

Upvotes: 1

Raja Jaganathan
Raja Jaganathan

Reputation: 36117

$('.submenu a').each(function() {
    var url = $(this).attr('href');
    var idx = url.lastIndexOf("/");
    url = url.substring(0, idx) + '#' + url.substring(idx+1);
    console.log(url);
});

Upvotes: 2

Mitya
Mitya

Reputation: 34556

Try this:

var str = "http://one/two/three/four";
console.log(str.replace(/\/(?=[^\/]*$)/, '#'));

That says: "replace the slash that is followed by either nothing or characters that do not include another slash, right to the end."

Upvotes: 8

Related Questions