1

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.