Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

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

share|improve this question

2 Answers 2

up vote 1 down vote accepted

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.

share|improve this answer

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');
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.