开发者

Replace string in URL with javascript

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, a开发者_如何学Pythonnd it returns a url with .* and \/ inside

any help? thanks


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜