views:

46

answers:

2

I need to replace a slash with a hash in a URL. Everything else stays the same.
e.g.:
this:

www.example.com/main/events/event-1  

needs to be changed to this:

www.example.com/main/events#event-1  

(jQuery solution is optimal, plugins OK)

Update based on OP's comment:

Using this code:

function outputStatus(e)
{
  if (e.success && $.url.segment(1) == 'events')
  {
    // IF Flash SWF loads success AND on events page
    var url = $.url.attr('source'); // gets current URL
    var new_url = url.replace(/\/([^\/]+)$/, "#$1"); // replaces last slash with a hash
    window.location = new_url; // sets the current URL to the new URL
  }
}

The URL is getting changed twice (so www.example.com/main/events/event-1 is becoming www.example.com/main/events#event-1 and then www.example.com/main#events#event-1).

+4  A: 

No jQuery needed, Javascript has native string replacement methods.

var url = "www.example.com/main/events/event-1"
var new_url = url.replace(/\/([^\/]+)$/, "#$1");
alert(new_url);

/\/([^\/]+)$/ will match the last slash and everything after it until the end of the string. $1 in the second argument is a backreference to the group created in the pattern (which contains everything after the final slash). Try it out!


Update:

My guess is that your outputStatus function is being called multiple times, and thus replacing multiple times. You can avoid this by checking for the presence of a # in your url first:

if (url.indexOf('#') == -1) // # is not found
{
  var new_url = url.replace(/\/([^\/]+)$/, "#$1");
}

String#indexOf will return a position if the value is found, and -1 if not.

Alternately (since it seems like you're using the jQuery URL Parser, correct?), you could check for the presence of $.url.attr('anchor') before modifying the url variable.

Daniel Vandersluis
this works, but it gets done 2X. using window.location = new_url; URL is first changed to: www.example.com/main/events#event-1 and then to: www.example.com/main#events#event-1 (2 hashes) just need it done 1X.
Ezn
[code] function outputStatus(e) { if (e.success // gets current URL var new_url = url.replace(/\/([^\/]+)$/, "#$1"); // replaces last slash with a hash window.location = new_url; //sets the current URL to the new URL } }[/code]
Ezn
(sorry about the line breaks, or lack thereof)
Ezn
+1  A: 

Try this:

var str = "www.example.com/main/events/event-1";

var idx = str.lastIndexOf('/');

var res = str.substr(0,idx) + '#' + str.substr(idx + 1);

or this:

var str = "www.example.com/main/events/event-1"

var res = str.replace(/\/([^/]+)$/,'#$1');
patrick dw