简体   繁体   中英

how to replace part of the URL with JavaScript?

I have something like http://domain.com/Pages/SearchResults.aspx?function=search&selectedserver=intranet&search_query=MyRecords and need to replace it by JavaScript with something similar to http://domain.com/Pages/SearchResults.aspx?function=loginsearch&user=admin&password=admin&selectedserver=intranet&search_query=MyRecords — so

function=search 

is being replaced with

function=loginsearch&user=admin&password=admin

inside the URL. Need help with what JavaScript should I save as a button on a browser's tool bar to click and have the URL in the address bar replaced.

var url = window.location.toString();
window.location = url.replace(/function=search/, 'function=loginsearch&user=admin&password=admin');

在不重新加载页面的情况下更新显示的 URL 的唯一方法是history.pushState

window.history.pushState('', '', '/your-new-url');
 location.href = location.href.replace(
    'function=search&', 'function=loginsearch&user=admin&password=admin&')

If you're wanting to do it without refreshing the page, I'm afraid that's impossible. You can only change the hash tag via Javascript, ie http://example.com/page/#hashtag , which you can do via window.location.hash .

UPDATE (11th September 2011): See the HTML5 history API DEMO and docs .

My version. Works fine for me.

let url = window.location.toString();
window.history.pushState('', '', url.replace(searching_string, new_string));

You may find the dedicated library URI.js helpful, particularly setQuery() and addQuery() methods. I pasted this chunk of code directly into the console on that page and it seems to work:

var url = 'http://domain.com/Pages/SearchResults.aspx?function=search&selectedserver=intranet&search_query=MyRecords';
var uri = new URI(url);
var new_params = {'function': 'loginsearch', 'user': 'admin', 'password': 'admin'};
uri.setSearch(new_params);
console.log(uri.toString());

http://domain.com/Pages/SearchResults.aspx?function=loginsearch&selectedserver=intranet&search_query=MyRecords&user=admin&password=admin
<- undefined
>

It should be easy to turn this logic into a function (or a one-liner :)). As an aside, why are you passing the credentials right in the URL?

var url             = window.location.href;               
window.location     = url.replace(/function=search/, 'function=loginsearch&user=admin&password=admin');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM