views:

63

answers:

2

Hello, I thought this was trivial but couldn't solve it out :(

I want to change a param passed in mu url with javascript.

var fullurl = window.location;
//do dome stuff to find var url.
fullurl.replace(/sort:.*\/direction:.*/g,'sort:' + url + '/direction:asc');

Basically there is a url like: http://example.com/article/ or http://example.com/article/sort:author/direction:asc

I the first case I don't want anything to be changed. In the second I want to replace the sort: with sort:url .

the above code doesn't seem to do anything. I think the problem is that the regexp isn't parsed, and it returns a url with .* and \/ inside

any help? thanks

+1  A: 

window.location is not a string, it is a special object which implicitly converts to a string. Further, string.replace returns the new value, it doesn't change the original string. Try something like this:

var fullurl = window.location.toString();
//do dome stuff to find var url.
window.location = fullurl.replace(/sort:.*\/direction:.*/g,'sort:' + url + '/direction:asc');
casablanca
+1  A: 

window.location is an object containing the following properties:

.hash
.host
.hostname
.href
.pathname
.port
.protocol
.search

You likely want to parse the href string. I did a preliminary test where I stubbed the url expectation and the replace worked except that you do not indicate what url is. Otherwise try the following in a console:

x = window.location.href
url = "SomeValue"
y = x.replace(/sort:.*\/direction:.*/g, 'sort:' + url + '/direction:asc')

you should get the result you are expecting assuming you inspect y and not x, since a replace operation returns a result and does not change the object itself.

Gabriel